Bird
0
0
DSA Cprogramming

Spiral Matrix Traversal in DSA C

Choose your learning style9 modes available
Mental Model
We walk around the edges of the matrix in a circle, moving inward layer by layer until all elements are visited.
Analogy: Imagine peeling an onion layer by layer, starting from the outer skin and moving towards the center, collecting all the layers as you go.
1 -> 2 -> 3 -> 4
↓           ↑
12         5
↓           ↑
11 10  9 -> 6
     ↑     ↓
     8 ← 7
Dry Run Walkthrough
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Goal: Print elements in spiral order: 1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7 -> 4 -> 5
Step 1: Traverse top row from left to right
Visited: 1 -> 2 -> 3
Remaining matrix:
[4,5,6]
[7,8,9]
Why: Start from the top edge to collect the first layer
Step 2: Traverse right column from top to bottom (excluding already visited top row)
Visited: 1 -> 2 -> 3 -> 6 -> 9
Remaining matrix:
[4,5]
[7,8]
Why: Move down the right edge to continue the spiral
Step 3: Traverse bottom row from right to left (excluding already visited right column)
Visited: 1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7
Remaining matrix:
[4,5]
Why: Move left along the bottom edge to complete the outer layer
Step 4: Traverse left column from bottom to top (excluding already visited bottom and top rows)
Visited: 1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7 -> 4
Remaining matrix:
[5]
Why: Move up the left edge to finish the outer layer
Step 5: Traverse the remaining middle element
Visited: 1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7 -> 4 -> 5
Why: Center element remains, add it to complete spiral
Result:
1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7 -> 4 -> 5
Annotated Code
DSA C
#include <stdio.h>

void spiralTraversal(int rows, int cols, int matrix[rows][cols]) {
    int top = 0, bottom = rows - 1;
    int left = 0, right = cols - 1;

    while (top <= bottom && left <= right) {
        // Traverse from left to right on top row
        for (int i = left; i <= right; i++) {
            printf("%d", matrix[top][i]);
            if (!(top == bottom && i == right)) printf(" -> ");
        }
        top++;

        // Traverse from top to bottom on right column
        for (int i = top; i <= bottom; i++) {
            printf("%d", matrix[i][right]);
            if (!(i == bottom && left == right)) printf(" -> ");
        }
        right--;

        if (top <= bottom) {
            // Traverse from right to left on bottom row
            for (int i = right; i >= left; i--) {
                printf("%d", matrix[bottom][i]);
                if (!(bottom == top && i == left)) printf(" -> ");
            }
            bottom--;
        }

        if (left <= right) {
            // Traverse from bottom to top on left column
            for (int i = bottom; i >= top; i--) {
                printf("%d", matrix[i][left]);
                if (!(i == top && left == right)) printf(" -> ");
            }
            left++;
        }
    }
    printf("\n");
}

int main() {
    int matrix[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    spiralTraversal(3, 3, matrix);
    return 0;
}
while (top <= bottom && left <= right) {
continue spiral while boundaries are valid
for (int i = left; i <= right; i++) {
traverse top row left to right
top++;
move top boundary down after top row traversal
for (int i = top; i <= bottom; i++) {
traverse right column top to bottom
right--;
move right boundary left after right column traversal
if (top <= bottom) { for (int i = right; i >= left; i--) {
traverse bottom row right to left if still valid
bottom--;
move bottom boundary up after bottom row traversal
if (left <= right) { for (int i = bottom; i >= top; i--) {
traverse left column bottom to top if still valid
left++;
move left boundary right after left column traversal
OutputSuccess
1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7 -> 4 -> 5
Complexity Analysis
Time: O(m*n) because each element in the m by n matrix is visited exactly once
Space: O(1) because traversal uses only a fixed number of variables for boundaries
vs Alternative: Compared to naive approaches that might revisit elements or use extra space, this method is efficient and uses constant extra space
Edge Cases
Empty matrix (0 rows or 0 columns)
No output is printed because the while loop condition fails immediately
DSA C
while (top <= bottom && left <= right) {
Single row matrix
Only the top row traversal runs, printing all elements left to right
DSA C
for (int i = left; i <= right; i++) {
Single column matrix
Only the right column traversal runs, printing all elements top to bottom
DSA C
for (int i = top; i <= bottom; i++) {
When to Use This Pattern
When you need to print or process matrix elements in a circular, inward pattern, use spiral traversal to systematically reduce boundaries and cover all elements.
Common Mistakes
Mistake: Not updating boundaries correctly causing infinite loops or repeated elements
Fix: After each edge traversal, update the corresponding boundary (top++, right--, bottom--, left++) 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 these traversals to avoid duplicates
Summary
Prints matrix elements in a spiral order starting from the top-left corner and moving inward.
Use when you want to visit all elements of a matrix in a circular pattern layer by layer.
The key is to keep track of four boundaries and move them inward after each edge traversal.