
π Spiral Matrix
π From 1D Arrays to the World of 2D Arrays (and Beyond!)
In my previous blog, we explored the basics of 1D Arrays β the simplest form of an array where elements are stored in a single line. We understood how they work, how to declare them, take input, and solve problems like searching, summing, and reversing elements.
Now, itβs time to level up! π―
Welcome to the world of 2D Arrays β a place where data is arranged not just in a line, but in rows and columns like a chessboard or a spreadsheet.
But before diving deep, letβs quickly recap what 1D, 2D, and even 3D arrays are
π Quick Recap of Array Dimensions
1D Array β
Think of it as a straight street with numbered houses. Each house has one value.
Example:
arr[5] = {1, 2, 3, 4, 5}
Visually:
[ 1 | 2 | 3 | 4 | 5 ]
2D Array β
Now imagine a grid or table with rows and columns β like a spreadsheet in Excel.
Example:
matrix[3][4]
Visually:
1 2 3 4
5 6 7 8
9 10 11 12
This is great for representing matrices, game boards, or tabular data.
3D Array β
Now, think of multiple 2D arrays stacked together β like pages in a book. Each page is a 2D grid, and flipping through pages gives you the third dimension.
Example:
cube[2][3][4]
#### Visualize: two layers, each of size 3Γ4.
π‘ Tip:
1D β List
2D β Table
3D β Book of tables
π Spiral Matrix Problem: Intuitive Guide with Diagram, Examples, Algorithm & Code
Let's dive into the famous Spiral Matrix problem, a favorite in coding interviews!
Problem Statement (Spiral Matrix)
Given an m x n matrix, return all elements of the matrix in spiral order.
Spiral order means starting from the top-left, going right, then down the edge, left at the bottom, up the other side, and then inward, βspiralingβ toward the center.
Example 1
Input:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Output:
[1, 2, 3, 6, 9, 8, 7, 4, 5]
Example 2
Input:
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
Output:
[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
Example 3
Input:
matrix = [
[1]
]
Output:
[1]
Visual Diagram: Spiral Traversal (3x3 example)
Here's how the spiral order visits a 3x3 matrix:
[ 1 β 2 β 3 ]
[ β β ]
[ 4 5 6 ]
[ β β 8 β 7 ]
Start top-left, go right β, down β, left β, up β, then repeat in the next inner "layer".
Detailed Algorithm Explanation
The solution goes layer by layer, keeping track of four boundaries:
top (first untraversed row)
bottom (last untraversed row)
left (first untraversed column)
right (last untraversed column)
Steps:
Move left to right across the top row. Increment top.
Move top to bottom down the right column. Decrement right.
If rows remain, move right to left across the bottom row. Decrement bottom.
If columns remain, move bottom to top up the left column. Increment left.
Repeat until all elements are traversed.
Code C++
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> result;
if (matrix.empty()) return result;
int top = 0, bottom = matrix.size() - 1;
int left = 0, right = matrix[0].size() - 1;
while (top <= bottom && left <= right) {
// Traverse top row
for (int j = left; j <= right; ++j)
result.push_back(matrix[top][j]);
top++;
// Traverse right column
for (int i = top; i <= bottom; ++i)
result.push_back(matrix[i][right]);
right--;
// Traverse bottom row (if any)
if (top <= bottom)
for (int j = right; j >= left; --j)
result.push_back(matrix[bottom][j]);
bottom--;
// Traverse left column (if any)
if (left <= right)
for (int i = bottom; i >= top; --i)
result.push_back(matrix[i][left]);
left++;
}
return result;
}
Java Code
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
if (matrix.length == 0) return result;
int top = 0, bottom = matrix.length - 1;
int left = 0, right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
for (int j = left; j <= right; ++j)
result.add(matrix[top][j]);
top++;
for (int i = top; i <= bottom; ++i)
result.add(matrix[i][right]);
right--;
if (top <= bottom)
for (int j = right; j >= left; --j)
result.add(matrix[bottom][j]);
bottom--;
if (left <= right)
for (int i = bottom; i >= top; --i)
result.add(matrix[i][left]);
left++;
}
return result;
}
Python Code
def spiralOrder(matrix):
result = []
if not matrix:
return result
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
while top <= bottom and left <= right:
for j in range(left, right + 1):
result.append(matrix[top][j])
top += 1
for i in range(top, bottom + 1):
result.append(matrix[i][right])
right -= 1
if top <= bottom:
for j in range(right, left - 1, -1):
result.append(matrix[bottom][j])
bottom -= 1
if left <= right:
for i in range(bottom, top - 1, -1):
result.append(matrix[i][left])
left += 1
return result
Time Complexity
Visits each element exactly once.
For an m x n matrix:
Time Complexity: O(m*n)
Space Complexity: O(m*n) for the result list/array.
4 Reactions
0 Bookmarks