Bird
Raised Fist0
DSA Javaprogramming~10 mins

Spiral Matrix Traversal in DSA Java - Execution Trace

Choose your learning style10 modes available
Concept Flow - Spiral Matrix Traversal
Initialize boundaries: top, bottom, left, right
↓
Traverse from left to right along top row
↓
Move top boundary down
↓
Traverse from top to bottom along right column
↓
Move right boundary left
↓
Traverse from right to left along bottom row
↓
Move bottom boundary up
↓
Traverse from bottom to top along left column
↓
Move left boundary right
↓
Check if boundaries crossed: top <= bottom and left <= right
↓
Repeat traversal
We keep four boundaries and move around the matrix edges in a spiral, shrinking boundaries after each side is traversed, until all elements are visited.
Execution Sample
DSA Java
int top = 0, bottom = m - 1;
int left = 0, right = n - 1;
while (top <= bottom && left <= right) {
  // Traverse edges in order
}
This code sets boundaries and loops to traverse the matrix edges in spiral order.
Execution Table
StepOperationBoundaries (top,bottom,left,right)Elements TraversedVisual State
1Initialize boundaries(0,2,0,2)[][[1,2,3],[4,5,6],[7,8,9]]
2Traverse left to right (top row)(0,2,0,2)[1,2,3][[1,2,3],[4,5,6],[7,8,9]]
3Move top boundary down(1,2,0,2)[1,2,3][[1,2,3],[4,5,6],[7,8,9]]
4Traverse top to bottom (right column)(1,2,0,2)[1,2,3,6,9][[1,2,3],[4,5,6],[7,8,9]]
5Move right boundary left(1,2,0,1)[1,2,3,6,9][[1,2,3],[4,5,6],[7,8,9]]
6Traverse right to left (bottom row)(1,2,0,1)[1,2,3,6,9,8,7][[1,2,3],[4,5,6],[7,8,9]]
7Move bottom boundary up(1,1,0,1)[1,2,3,6,9,8,7][[1,2,3],[4,5,6],[7,8,9]]
8Traverse bottom to top (left column)(1,1,0,1)[1,2,3,6,9,8,7,4][[1,2,3],[4,5,6],[7,8,9]]
9Move left boundary right(1,1,1,1)[1,2,3,6,9,8,7,4][[1,2,3],[4,5,6],[7,8,9]]
10Traverse left to right (top row)(1,1,1,1)[1,2,3,6,9,8,7,4,5][[1,2,3],[4,5,6],[7,8,9]]
11Move top boundary down(2,1,1,1)[1,2,3,6,9,8,7,4,5][[1,2,3],[4,5,6],[7,8,9]]
12Check boundaries top <= bottom and left <= right(2,1,1,1)[1,2,3,6,9,8,7,4,5][Traversal ends]
💡 top (2) > bottom (1), so traversal stops
Variable Tracker
VariableStartAfter Step 3After Step 5After Step 7After Step 9After Step 11Final
top0111122
bottom2221111
left0000111
right2211111
elements_traversed[][1,2,3][1,2,3,6,9][1,2,3,6,9,8,7][1,2,3,6,9,8,7,4][1,2,3,6,9,8,7,4,5][1,2,3,6,9,8,7,4,5]
Key Moments - 3 Insights
Why do we move the boundaries after each edge traversal?
Moving boundaries after traversing an edge prevents revisiting the same row or column. For example, after step 2, top moves down to avoid re-traversing the top row (see execution_table rows 2 and 3).
Why does the loop stop when top > bottom or left > right?
The loop stops because all rows or columns have been covered. At step 12, top (2) is greater than bottom (1), so no more valid rows remain (see execution_table row 12).
How do we know which direction to traverse next?
We follow the fixed order: left to right, top to bottom, right to left, bottom to top, then repeat. This order ensures a spiral pattern (see concept_flow).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 6, which elements have been traversed so far?
A[1,2,3,6,9]
B[1,2,3,6,9,8,7]
C[1,2,3]
D[1,2,3,6]
💡 Hint
Check the 'Elements Traversed' column at step 6 in execution_table.
At which step does the left boundary move right for the first time?
AStep 9
BStep 7
CStep 5
DStep 3
💡 Hint
Look at the 'Operation' and 'Boundaries' columns to see when left changes from 0 to 1.
If the matrix had 4 rows instead of 3, how would the final step number change?
AIt would stay the same
BIt would decrease because boundaries cross sooner
CIt would increase because more elements exist
DIt would be unpredictable
💡 Hint
More rows mean more elements to traverse, so more steps are needed (see variable_tracker for boundaries).
Concept Snapshot
Spiral Matrix Traversal:
- Use four boundaries: top, bottom, left, right
- Traverse edges in order: left→right, top→bottom, right→left, bottom→top
- After each edge, move the corresponding boundary inward
- Continue while top ≤ bottom and left ≤ right
- Collect elements in spiral order without repeats
Full Transcript
Spiral Matrix Traversal uses four boundaries to track the edges of the matrix. We start by traversing the top row from left to right, then move the top boundary down. Next, we traverse the right column from top to bottom, then move the right boundary left. Then we traverse the bottom row from right to left, moving the bottom boundary up, and finally traverse the left column from bottom to top, moving the left boundary right. We repeat this process until the top boundary crosses the bottom or the left boundary crosses the right, meaning all elements have been visited. This method ensures all elements are collected in a spiral order without repetition.

Practice

(1/5)
1. What is the main idea behind Spiral Matrix Traversal?
easy
A. Traverse the matrix in a circular pattern from outer to inner layers
B. Traverse the matrix row by row from top to bottom
C. Traverse the matrix column by column from left to right
D. Traverse only the diagonal elements of the matrix

Solution

  1. Step 1: Understand traversal pattern

    Spiral traversal means moving around the edges of the matrix and gradually moving inward in a circular way.
  2. Step 2: Compare options

    Only Traverse the matrix in a circular pattern from outer to inner layers describes moving in a circular pattern from outer to inner layers, which matches spiral traversal.
  3. Final Answer:

    Traverse the matrix in a circular pattern from outer to inner layers -> Option A
  4. Quick Check:

    Spiral traversal = circular outer to inner [OK]
Hint: Spiral means circle inward from edges [OK]
Common Mistakes:
  • Confusing spiral with row-wise traversal
  • Thinking spiral means diagonal only
  • Mixing column-wise with spiral
2. Which of the following Java code snippets correctly initializes the boundaries for spiral traversal of a matrix int[][] matrix?
easy
A. int top = 1, bottom = matrix.length, left = 1, right = matrix[0].length;
B. int top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1;
C. int top = 0, bottom = matrix[0].length - 1, left = 0, right = matrix.length - 1;
D. int top = matrix.length, bottom = 0, left = matrix[0].length, right = 0;

Solution

  1. Step 1: Identify matrix dimensions

    For a 2D array, rows = matrix.length, columns = matrix[0].length.
  2. Step 2: Set boundaries correctly

    Top and left start at 0, bottom is last row index (length-1), right is last column index (length-1). int top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1; matches this.
  3. Final Answer:

    int top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1; -> Option B
  4. Quick Check:

    Boundaries start at 0 and end at length-1 [OK]
Hint: Boundaries start at 0, end at length-1 [OK]
Common Mistakes:
  • Using 1-based indices instead of 0-based
  • Swapping rows and columns in boundaries
  • Setting bottom or right greater than max index
3. What is the output of the following Java code snippet for spiral traversal?
int[][] matrix = {
  {1, 2, 3},
  {4, 5, 6},
  {7, 8, 9}
};

int top = 0, bottom = 2, left = 0, right = 2;

while (top <= bottom && left <= right) {
  for (int i = left; i <= right; i++) System.out.print(matrix[top][i] + " ");
  top++;
  for (int i = top; i <= bottom; i++) System.out.print(matrix[i][right] + " ");
  right--;
  if (top <= bottom) {
    for (int i = right; i >= left; i--) System.out.print(matrix[bottom][i] + " ");
    bottom--;
  }
  if (left <= right) {
    for (int i = bottom; i >= top; i--) System.out.print(matrix[i][left] + " ");
    left++;
  }
}
medium
A. 1 4 7 8 9 6 3 2 5
B. 1 2 3 4 5 6 7 8 9
C. 1 2 3 6 9 8 7 4 5
D. 9 8 7 6 5 4 3 2 1

Solution

  1. Step 1: Trace first outer layer

    Top row: 1 2 3, right column down: 6 9, bottom row left: 8 7, left column up: 4
  2. Step 2: Trace inner layer

    Now top=1, bottom=1, left=1, right=1, print center element: 5
  3. Final Answer:

    1 2 3 6 9 8 7 4 5 -> Option C
  4. Quick Check:

    Spiral order matches 1 2 3 6 9 8 7 4 5 [OK]
Hint: Follow boundaries and print edges inward [OK]
Common Mistakes:
  • Printing rows or columns in wrong order
  • Missing center element in odd-sized matrix
  • Not updating boundaries correctly
4. Identify the bug in this spiral traversal code snippet:
int top = 0, bottom = matrix.length - 1;
int left = 0, right = matrix[0].length - 1;
while (top < bottom && left < right) {
  for (int i = left; i <= right; i++) System.out.print(matrix[top][i] + " ");
  top++;
  for (int i = top; i <= bottom; i++) System.out.print(matrix[i][right] + " ");
  right--;
  for (int i = right; i >= left; i--) System.out.print(matrix[bottom][i] + " ");
  bottom--;
  for (int i = bottom; i >= top; i--) System.out.print(matrix[i][left] + " ");
  left++;
}
medium
A. The while condition should use <= instead of < to include all layers
B. The for loops should use < instead of <= to avoid index errors
C. The boundaries are initialized incorrectly
D. The print statements should be inside if conditions to avoid duplicates

Solution

  1. Step 1: Analyze while loop condition

    Using < excludes the case when top == bottom or left == right, missing last layer in odd-sized matrices.
  2. Step 2: Correct condition to include all layers

    Changing to <= ensures the center or last layer is processed.
  3. Final Answer:

    The while condition should use <= instead of < to include all layers -> Option A
  4. Quick Check:

    Use <= in while to cover all layers [OK]
Hint: Use <= in while to cover all matrix layers [OK]
Common Mistakes:
  • Using < excludes center element in odd matrices
  • Not updating boundaries after each loop
  • Missing if checks for inner loops
5. Given a rectangular matrix of size 3x4:
int[][] matrix = {
  {1, 2, 3, 4},
  {5, 6, 7, 8},
  {9, 10, 11, 12}
};

What is the spiral traversal output?
hard
A. 1 5 9 10 11 12 8 4 3 2 6 7
B. 1 2 3 4 8 12 11 10 9 5 7 6
C. 1 2 3 4 8 12 11 10 9 6 5 7
D. 1 2 3 4 8 12 11 10 9 5 6 7

Solution

  1. Step 1: Traverse top row left to right

    Print 1 2 3 4
  2. Step 2: Traverse right column top to bottom

    Print 8 12
  3. Step 3: Traverse bottom row right to left

    Print 11 10 9
  4. Step 4: Traverse left column bottom to top

    Print 5
  5. Step 5: Traverse inner row left to right

    Print 6 7
  6. Final Answer:

    1 2 3 4 8 12 11 10 9 5 6 7 -> Option D
  7. Quick Check:

    Follow edges inward for rectangular matrix [OK]
Hint: Print edges clockwise, move inward layer by layer [OK]
Common Mistakes:
  • Mixing order of inner elements
  • Skipping last inner row
  • Confusing left column traversal direction
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard