Bird
Raised Fist0
DSA C#programming

Spiral Matrix Traversal in DSA C#

Choose your learning style10 modes available
Mental Model
We walk around the edges of the matrix in a circle, then move inward layer by layer until all elements are visited.
Analogy: Imagine peeling an onion layer by layer, starting from the outer skin and moving inward, collecting all parts as you go.
1  2  3  4
12 13 14 5
11 16 15 6
10 9  8  7
↑start at top-left corner, move right ->
Dry Run Walkthrough
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Goal: Traverse the matrix in spiral order and collect elements in that sequence
Step 1: Traverse top row from left to right
Visited: 1 -> 2 -> 3
Remaining matrix edges shrink inward
Why: Start by collecting the top row elements in order
Step 2: Traverse right column from top to bottom (excluding already visited top row)
Visited: 1 -> 2 -> 3 -> 6 -> 9
Edges shrink inward
Why: Collect the rightmost column elements after top row
Step 3: Traverse bottom row from right to left (excluding visited right column)
Visited: 1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7
Edges shrink inward
Why: Collect bottom row elements moving left
Step 4: Traverse left column from bottom to top (excluding visited bottom row and top row)
Visited: 1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7 -> 4
Edges shrink inward
Why: Collect left column elements moving up
Step 5: Traverse the inner remaining element(s) if any
Visited: 1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7 -> 4 -> 5
No more elements left
Why: Collect the center element after completing outer layers
Result:
1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7 -> 4 -> 5 -> null
Annotated Code
DSA C#
using System;
using System.Collections.Generic;

class SpiralMatrixTraversal {
    public static List<int> SpiralOrder(int[][] matrix) {
        List<int> result = new List<int>();
        if (matrix == null || matrix.Length == 0) return result;

        int top = 0;
        int bottom = matrix.Length - 1;
        int left = 0;
        int right = matrix[0].Length - 1;

        while (top <= bottom && left <= right) {
            // Traverse from left to right on top row
            for (int i = left; i <= right; i++) {
                result.Add(matrix[top][i]);
            }
            top++;

            // Traverse from top to bottom on right column
            for (int i = top; i <= bottom; i++) {
                result.Add(matrix[i][right]);
            }
            right--;

            if (top <= bottom) {
                // Traverse from right to left on bottom row
                for (int i = right; i >= left; i--) {
                    result.Add(matrix[bottom][i]);
                }
                bottom--;
            }

            if (left <= right) {
                // Traverse from bottom to top on left column
                for (int i = bottom; i >= top; i--) {
                    result.Add(matrix[i][left]);
                }
                left++;
            }
        }

        return result;
    }

    static void Main() {
        int[][] matrix = new int[][] {
            new int[] {1, 2, 3},
            new int[] {4, 5, 6},
            new int[] {7, 8, 9}
        };

        List<int> spiral = SpiralOrder(matrix);
        Console.WriteLine(string.Join(" -> ", spiral) + " -> null");
    }
}
while (top <= bottom && left <= right) {
continue looping while there are layers left to traverse
for (int i = left; i <= right; i++) { result.Add(matrix[top][i]); }
traverse top row from left to right
top++;
move top boundary down after traversing top row
for (int i = top; i <= bottom; i++) { result.Add(matrix[i][right]); }
traverse right column from top to bottom
right--;
move right boundary left after traversing right column
if (top <= bottom) { for (int i = right; i >= left; i--) { result.Add(matrix[bottom][i]); } bottom--; }
traverse bottom row from right to left if still valid, then move bottom boundary up
if (left <= right) { for (int i = bottom; i >= top; i--) { result.Add(matrix[i][left]); } left++; }
traverse left column from bottom to top if still valid, then move left boundary right
OutputSuccess
1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7 -> 4 -> 5 -> null
Complexity Analysis
Time: O(m*n) because every element in the m by n matrix is visited exactly once
Space: O(m*n) for the output list that stores all elements of the matrix
vs Alternative: Compared to naive repeated scanning, this approach visits each element once in a controlled spiral order, avoiding repeated visits and extra checks
Edge Cases
Empty matrix
Returns empty list immediately
DSA C#
if (matrix == null || matrix.Length == 0) return result;
Single row matrix
Traverses the single row left to right correctly
DSA C#
while (top <= bottom && left <= right)
Single column matrix
Traverses the single column top to bottom correctly
DSA C#
while (top <= bottom && left <= right)
When to Use This Pattern
When you need to visit all elements of a matrix in a circular, inward pattern, use spiral traversal to systematically peel layers from outside to inside.
Common Mistakes
Mistake: Not updating boundaries correctly causing infinite loops or repeated elements
Fix: After traversing each side, update the corresponding boundary (top, bottom, left, right) to move inward
Mistake: Not checking boundary conditions before traversing bottom row or left column
Fix: Add checks like if (top <= bottom) and if (left <= right) before those traversals
Summary
It collects matrix elements in a spiral order starting from the outer layer moving inward.
Use it when you want to read or print matrix elements in a circular inward pattern.
The key is to keep track of four boundaries and move them inward after each side traversal.

Practice

(1/5)
1. What is the main idea behind Spiral Matrix Traversal?
easy
A. To visit all elements of a matrix in a spiral order starting from the top-left corner
B. To sort the matrix elements in ascending order
C. To find the maximum element in each row of the matrix
D. To transpose the matrix by swapping rows and columns

Solution

  1. Step 1: Understand traversal pattern

    Spiral traversal means visiting matrix elements starting from the outer layer and moving inward in a circular pattern.
  2. Step 2: Identify the traversal goal

    The goal is to visit every element exactly once in a spiral order, usually starting from the top-left corner.
  3. Final Answer:

    To visit all elements of a matrix in a spiral order starting from the top-left corner -> Option A
  4. Quick Check:

    Spiral traversal = visiting elements in spiral order [OK]
Hint: Think of peeling an onion layer by layer in a circle [OK]
Common Mistakes:
  • Confusing spiral traversal with sorting
  • Thinking it only visits diagonal elements
  • Assuming it transposes the matrix
2. Which of the following C# code snippets correctly initializes the boundaries for spiral traversal of a matrix named matrix?
easy
A. int top = 0, bottom = matrix.Length - 1, left = 0, right = matrix.GetLength(0) - 1;
B. int top = 1, bottom = matrix.Length, left = 1, right = matrix.Length;
C. int top = matrix.GetLength(1), bottom = 0, left = matrix.GetLength(0), right = 0;
D. int top = 0, bottom = matrix.GetLength(0) - 1, left = 0, right = matrix.GetLength(1) - 1;

Solution

  1. Step 1: Understand matrix dimensions in C#

    matrix.GetLength(0) gives number of rows, matrix.GetLength(1) gives number of columns.
  2. Step 2: Set boundaries correctly

    Top and left start at 0; bottom and right are last indices (length - 1) for rows and columns respectively.
  3. Final Answer:

    int top = 0, bottom = matrix.GetLength(0) - 1, left = 0, right = matrix.GetLength(1) - 1; -> Option D
  4. Quick Check:

    Correct boundary initialization = int top = 0, bottom = matrix.GetLength(0) - 1, left = 0, right = matrix.GetLength(1) - 1; [OK]
Hint: Use GetLength(0) for rows, GetLength(1) for columns [OK]
Common Mistakes:
  • Using matrix.Length which is total elements, not rows or columns
  • Swapping rows and columns in GetLength calls
  • Starting boundaries at 1 instead of 0
3. What is the output of the following C# code snippet for spiral traversal?
int[,] matrix = {
  {1, 2, 3},
  {4, 5, 6},
  {7, 8, 9}
};

List<int> result = new List<int>();
int top = 0, bottom = 2, left = 0, right = 2;

while (top <= bottom && left <= right) {
  for (int i = left; i <= right; i++) result.Add(matrix[top, i]);
  top++;
  for (int i = top; i <= bottom; i++) result.Add(matrix[i, right]);
  right--;
  if (top <= bottom) {
    for (int i = right; i >= left; i--) result.Add(matrix[bottom, i]);
    bottom--;
  }
  if (left <= right) {
    for (int i = bottom; i >= top; i--) result.Add(matrix[i, left]);
    left++;
  }
}
Console.WriteLine(string.Join(", ", result));
medium
A. 1, 2, 3, 6, 9, 8, 7, 4, 5
B. 1, 4, 7, 8, 9, 6, 3, 2, 5
C. 1, 2, 3, 4, 5, 6, 7, 8, 9
D. 9, 8, 7, 6, 5, 4, 3, 2, 1

Solution

  1. Step 1: Traverse top row left to right

    Elements added: 1, 2, 3; then top moves from 0 to 1.
  2. Step 2: Traverse right column top to bottom

    Elements added: 6, 9; right moves from 2 to 1.
  3. Step 3: Traverse bottom row right to left

    Elements added: 8, 7; bottom moves from 2 to 1.
  4. Step 4: Traverse left column bottom to top

    Elements added: 4; left moves from 0 to 1.
  5. Step 5: Repeat for inner layer

    Now top=1, bottom=1, left=1, right=1; add element 5.
  6. Final Answer:

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

    Spiral order of 3x3 matrix = 1, 2, 3, 6, 9, 8, 7, 4, 5 [OK]
Hint: Follow boundaries and shrink after each side [OK]
Common Mistakes:
  • Not updating boundaries correctly after each side
  • Skipping the inner elements
  • Reversing traversal directions incorrectly
4. Identify the bug in this spiral traversal code snippet and select the fix:
int top = 0, bottom = matrix.GetLength(0), left = 0, right = matrix.GetLength(1) - 1;
while (top <= bottom && left <= right) {
  for (int i = left; i <= right; i++) Console.Write(matrix[top, i] + " ");
  top++;
  for (int i = top; i <= bottom; i++) Console.Write(matrix[i, right] + " ");
  right--;
  if (top <= bottom) {
    for (int i = right; i >= left; i--) Console.Write(matrix[bottom, i] + " ");
    bottom--;
  }
  if (left <= right) {
    for (int i = bottom; i >= top; i--) Console.Write(matrix[i, left] + " ");
    left++;
  }
}
medium
A. Change right to matrix.GetLength(1) to include last column
B. Change bottom to matrix.GetLength(0) - 1 to avoid index out of range
C. Remove the if conditions checking top <= bottom and left <= right
D. Initialize top and left to 1 instead of 0

Solution

  1. Step 1: Check boundary initialization

    bottom is set to matrix.GetLength(0), which is out of index range since indexing is zero-based.
  2. Step 2: Correct bottom boundary

    bottom should be matrix.GetLength(0) - 1 to point to the last valid row index.
  3. Final Answer:

    Change bottom to matrix.GetLength(0) - 1 to avoid index out of range -> Option B
  4. Quick Check:

    Zero-based indexing means last index = length - 1 [OK]
Hint: Remember zero-based indexing means last index = length - 1 [OK]
Common Mistakes:
  • Using length instead of length - 1 for last index
  • Removing boundary checks causing infinite loops
  • Starting indices at 1 instead of 0
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, 2, 3, 4, 8, 12, 9, 10, 11, 5, 6, 7
B. 1, 5, 9, 10, 11, 12, 8, 4, 3, 2, 6, 7
C. 1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7
D. 1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 7, 6

Solution

  1. Step 1: Traverse top row left to right

    Elements: 1, 2, 3, 4; top moves from 0 to 1.
  2. Step 2: Traverse right column top to bottom

    Elements: 8, 12; right moves from 3 to 2.
  3. Step 3: Traverse bottom row right to left

    Elements: 11, 10, 9; bottom moves from 2 to 1.
  4. Step 4: Traverse left column bottom to top

    Elements: 5; left moves from 0 to 1.
  5. Step 5: Traverse inner row left to right

    Elements: 6, 7; top moves from 1 to 2.
  6. Final Answer:

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

    Spiral order of 3x4 matrix = 1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7 [OK]
Hint: Shrink boundaries after each side, watch rectangular shape [OK]
Common Mistakes:
  • Mixing order of inner elements
  • Skipping last inner row or column
  • Confusing left and right boundaries
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