medium Spiral Matrix III
Problem Statement
You are given four positive integers rows, cols, rStart, and cStart. You start at cell (rStart, cStart) in a grid of size rows x cols. The grid's top-left corner is at (0, 0) and the bottom-right corner is at (rows-1, cols-1).
You need to visit every cell of this grid by walking in a clockwise spiral pattern. If you move outside the grid's boundaries, you continue walking outside but will return to the grid later.
Return an array of coordinates representing the order of cells visited during this walk.
Examples
- Example 1:
- Input: rows =
4, cols =4, rStart =2, cStart =2
- Output: [[2,2],[2,3],[3,3],[3,2],[3,1],[2,1],[1,1],[1,2],[1,3],[3,0],[2,0],[1,0],[0,0],[0,1],[0,2],[0,3]]
- Explanation: Start at (2,2), move right to (2,3), down to (3,3), left to (3,2), (3,1), up to (2,1), and continue to other cells in a similar way.
- Example 2:
- Input: rows =
3, cols =3, rStart =0, cStart =0
- Output: [[0,0],[0,1],[1,1],[1,0],[0,2],[1,2],[2,2],[2,1],[2,0]]
- Explanation: Start at (0,0), move right to (0,1), continue down to (1,1), then left to (1,0), then out of boundary and reach to (0,2), down to (1,2), (2,2), and finally left to (2,1), (2, 0).
- Example 3:
- Input: rows =
5, cols =5, rStart =4, cStart =4 - Output: [[4,4],[4,3],[3,3],[3,4],[4,2],[3,2],[2,2],[2,3],[2,4],[4,1],[3,1],[2,1],[1,1],[1,2],[1,3],[1,4],[4,0],[3,0],[2,0],[1,0],[0,0],[0,1],[0,2],[0,3],[0,4]]
- Explanation: Output shows the spiral matrix traversal according to the problem statement.
Constraints:
- 1 <= rows, cols <= 100
- 0 <= rStart < rows
- 0 <= cStart < cols
Try it yourself
Try solving this question here:
✅ Solution Spiral Matrix III
Problem Statement
You are given four positive integers rows, cols, rStart, and cStart. You start at cell (rStart, cStart) in a grid of size rows x cols. The grid's top-left corner is at (0, 0) and the bottom-right corner is at (rows-1, cols-1).
You need to visit every cell of this grid by walking in a clockwise spiral pattern. If you move outside the grid's boundaries, you continue walking outside but will return to the grid later.
Return an array of coordinates representing the order of cells visited during this walk.
Examples
- Example 1:
- Input: rows =
4, cols =4, rStart =2, cStart =2
- Output: [[2,2],[2,3],[3,3],[3,2],[3,1],[2,1],[1,1],[1,2],[1,3],[3,0],[2,0],[1,0],[0,0],[0,1],[0,2],[0,3]]
- Explanation: Start at (2,2), move right to (2,3), down to (3,3), left to (3,2), (3,1), up to (2,1), and continue to other cells in a similar way.
- Example 2:
- Input: rows =
3, cols =3, rStart =0, cStart =0
- Output: [[0,0],[0,1],[1,1],[1,0],[0,2],[1,2],[2,2],[2,1],[2,0]]
- Explanation: Start at (0,0), move right to (0,1), continue down to (1,1), then left to (1,0), then out of boundary and reach to (0,2), down to (1,2), (2,2), and finally left to (2,1), (2, 0).
- Example 3: - Input: rows =
5, cols =5, rStart =4, cStart =4
- Output: [[4,4],[4,3],[3,3],[3,4],[4,2],[3,2],[2,2],[2,3],[2,4],[4,1],[3,1],[2,1],[1,1],[1,2],[1,3],[1,4],[4,0],[3,0],[2,0],[1,0],[0,0],[0,1],[0,2],[0,3],[0,4]]
- Explanation: Output shows the spiral matrix traversal according to the problem statement.
Constraints:
- 1 <= rows, cols <= 100
- 0 <= rStart < rows
- 0 <= cStart < cols
Solution
To solve this problem, we'll simulate the movement in a spiral pattern starting from the given initial cell. We'll maintain the current direction, changing directions when necessary to cover the entire grid. We'll keep moving in the current direction until we need to turn, ensuring we cover all cells. The traversal continues even if the current cell goes out of bounds, ensuring we eventually return to valid cells. This method ensures all cells are visited systematically and in the correct order. We'll store the coordinates of the visited cells in a result array.
Step-by-Step Algorithm
-
Initialize Variables:
- Create a 2D array
resultto store the coordinates of cells in the order they are visited. - Set initial direction to right (
dx = 0,dy = 1). - Initialize
numVisited = 0to keep track of the number of cells visited. - Initialize
directionChange = 0to count the number of direction changes. - Use a temporary variable
tempfor swapping directions.
- Create a 2D array
-
Loop Until All Cells Are Visited:
- While
numVisited < rows * cols:- This ensures we visit all cells in the grid.
- Increment
directionChangeat the start of each iteration to handle the next direction change.
- While
-
Move in the Current Direction:
- For each step in the range
0todirectionChange // 2 + 1:- The number of steps taken in each direction increases by one after every two direction changes, ensuring the spiral pattern.
- Check if the current cell is within grid boundaries:
- If
0 <= rStart < rowsand0 <= cStart < cols:- Record the cell's coordinates in
resultand incrementnumVisited.
- Record the cell's coordinates in
- If
- Move to the next cell in the current direction by updating
rStartandcStartwithdxanddy.
- For each step in the range
-
Change Direction:
- After completing the steps in the current direction:
- Swap directions:
- Use
tempto temporarily holddx. - Update
dxtodyanddyto-tempto change direction in the order: right -> down -> left -> up.
- Use
- Swap directions:
- After completing the steps in the current direction:
-
Return the Result:
- After all cells are visited, return the
resultarray containing the coordinates of cells in the spiral order.
- After all cells are visited, return the
Algorithm Walkthrough
For rows = 4, cols = 4, rStart = 2, cStart = 2:
-
Initialization:
result = []- Initial direction: right (
dx = 0, dy = 1) numVisited = 0directionChange = 0- Starting cell:
(2, 2)
-
Traversal:
-
Step 1:
- Move right 1 step:
- Visit
(2, 2), append toresult, incrementnumVisitedto 1 rStart = 2, cStart = 3
- Visit
- Change direction to down:
dx = 1, dy = 0
- Increment
directionChangeto 1
- Move right 1 step:
-
Step 2:
- Move down 1 step:
- Visit
(2, 3), append toresult, incrementnumVisitedto 2 rStart = 3, cStart = 3
- Visit
- Change direction to left:
dx = 0, dy = -1
- Increment
directionChangeto 2
- Move down 1 step:
-
Step 3:
- Move left 2 steps:
- Visit
(3, 3), append toresult, incrementnumVisitedto 3 rStart = 3, cStart = 2- Visit
(3, 2), append toresult, incrementnumVisitedto 4 rStart = 3, cStart = 1
- Visit
- Change direction to up:
dx = -1, dy = 0
- Increment
directionChangeto 3
- Move left 2 steps:
-
Step 4:
- Move up 2 steps:
- Visit
(3, 1), append toresult, incrementnumVisitedto 5 rStart = 2, cStart = 1- Visit
(2, 1), append toresult, incrementnumVisitedto 6 rStart = 1, cStart = 1
- Visit
- Change direction to right:
dx = 0, dy = 1
- Increment
directionChangeto 4
- Move up 2 steps:
-
Step 5:
- Move right 3 steps:
- Visit
(1, 1), append toresult, incrementnumVisitedto 7 rStart = 1, cStart = 2- Visit
(1, 2), append toresult, incrementnumVisitedto 8 rStart = 1, cStart = 3- Visit
(1, 3), append toresult, incrementnumVisitedto 9 rStart = 1, cStart = 4(out of bounds)
- Visit
- Change direction to down:
dx = 1, dy = 0
- Increment
directionChangeto 5
- Move right 3 steps:
-
Step 6:
- Move down 3 steps:
- Visit
(2, 4),(3, 4), and(4, 4). All are out of bounds.
- Visit
- Change direction to left:
dx = 0, dy = -1
- Increment
directionChangeto 6
- Move down 3 steps:
-
Step 7:
- Move left 4 steps:
- Visit
(4, 3),(4, 2),(4, 1)and(4, 0). All are out of bounds.
- Visit
- Change direction to up:
dx = -1, dy = 0
- Increment
directionChangeto 7
- Move left 4 steps:
-
Step 8:
- Move up 4 steps:
- Visit
(3, 0), append toresult, incrementnumVisitedto 10 rStart = 2, cStart = 0- Visit
(2, 0), append toresult, incrementnumVisitedto 11 rStart = 1, cStart = 0- Visit
(1, 0), append toresult, incrementnumVisitedto 12 rStart = 0, cStart = 0- Visit
(0, 0), append toresult, incrementnumVisitedto 13 rStart = 0, cStart = 1
- Visit
- Change direction to right:
dx = 0, dy = 1
- Increment
directionChangeto 8
- Move up 4 steps:
-
Step 9:
- Move right 5 steps:
- Visit
(0, 1), append toresult, incrementnumVisitedto 14 rStart = 0, cStart = 2- Visit
(0, 2), append toresult, incrementnumVisitedto 15 rStart = 0, cStart = 3- Visit
(0, 3), append toresult, incrementnumVisitedto 16 rStart = 0, cStart = 4- Visit other elements but which are out of bounds.
- Visit
- Move right 5 steps:
-
-
Return Result:
- Once all cells are visited, return the
resultarray containing the coordinates of visited cells.
- Once all cells are visited, return the
The final output will be:
[[2,2],[2,3],[3,3],[3,2],[3,1],[2,1],[1,1],[1,2],[1,3],[3,0],[2,0],[1,0],[0,0],[0,1],[0,2],[0,3]]
Code
public class Solution {
public int[][] spiralMatrixIII(int rows, int cols, int rStart, int cStart) {
int[][] result = new int[rows * cols][2];
int dx = 0,
dy = 1; // Initial direction: right
int numVisited = 0; // Number of cells visited
int directionChange = 0; // Number of direction changes
int temp; // Temporary variable for swapping directions
for (int steps = 0; numVisited < rows * cols; ++directionChange) {
for (int step = 0; step < directionChange / 2 + 1; ++step) {
// Check if the current cell is within grid boundaries
if (
0 <= rStart && rStart < rows && 0 <= cStart && cStart < cols
) result[numVisited++] = new int[] { rStart, cStart };
// Move to the next cell in the current direction
rStart += dx;
cStart += dy;
}
// Change direction: right -> down -> left -> up
temp = dx;
dx = dy;
dy = -temp;
}
return result;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[][] result1 = solution.spiralMatrixIII(4, 4, 2, 2);
printResult(result1);
int[][] result2 = solution.spiralMatrixIII(3, 3, 0, 0);
printResult(result2);
int[][] result3 = solution.spiralMatrixIII(5, 5, 4, 4);
printResult(result3);
}
private static void printResult(int[][] result) {
for (int[] cell : result) {
System.out.print("[" + cell[0] + "," + cell[1] + "] ");
}
System.out.println();
}
}
Complexity Analysis
Time Complexity:
- The algorithm iterates over each cell of the grid exactly once. Since the total number of cells is
rows * cols, the time complexity is.
Space Complexity:
- The result array stores the coordinates of all cells in the grid, which requires space proportional to the number of cells. Thus, the space complexity is
.
🤖 Don't fully get this? Learn it with Claude
Stuck on Spiral Matrix III? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Spiral Matrix III** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Spiral Matrix III** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Spiral Matrix III**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Spiral Matrix III**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.