Spiral Matrix
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,3,6,9,8,7,4,5] Example 2:
Input: [ [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]
Solution:
- Use dir to indicate direction 0,1,2,3
- Use rLow, rHigh and cLow, cHigh to mark range
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.empty() || matrix.front().empty()) return {};
int dir = 0;
int rLow = 0, rHigh = matrix.size()-1;
int cLow = 0, cHigh = matrix.front().size()-1;
vector<int> ans;
while (rLow <= rHigh && cLow <= cHigh) {
if (dir == 0) {
// Right
for (int i=cLow; i<=cHigh; i++) {
ans.push_back(matrix[rLow][i]);
}
rLow += 1;
} else if (dir == 1) {
// Down
for (int i=rLow; i<=rHigh; i++) {
ans.push_back(matrix[i][cHigh]);
}
cHigh -= 1;
} else if (dir == 2) {
// Left
for (int i=cHigh; i>=cLow; i--) {
ans.push_back(matrix[rHigh][i]);
}
rHigh -= 1;
} else if (dir == 3) {
// Up
for (int i=rHigh; i>=rLow; i--) {
ans.push_back(matrix[i][cLow]);
}
cLow += 1;
}
dir = (dir + 1) % 4;
}
return ans;
}
vector<int> spiralOrder(vector<vector<int>>& matrix) {
// 1. We start from position (0, 0)
// 2. Follow the order right, down, left, up
// 3. We change the direction each time we meet the boarder or visited position.
// Corner case
if (matrix.empty() || matrix.front().empty()) return {};
// Init currrent direction and four directions
int dir = 0;
vector<vector<int>> dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
// Init current position
int row = 0, col = 0;
// Use range to mark the left and right bound, top and bottom bound
int rowTop = 0, rowBottom = matrix.size()-1;
int colLeft = 0, colRight = matrix.front().size()-1;
vector<int> ans;
while (rowTop <= rowBottom && colLeft <= colRight) {
// Move towards one direction
while (row >= rowTop && row <= rowBottom &&
col >= colLeft && col <= colRight) {
ans.push_back(matrix[row][col]);
row += dirs[dir][0];
col += dirs[dir][1];
}
// Shrink range based on direction
if (dir == 0) {
rowTop += 1;
} else if (dir == 1) {
colRight -= 1;
} else if (dir == 2) {
rowBottom -= 1;
} else {
colLeft += 1;
}
// Step back one position
row -= dirs[dir][0];
col -= dirs[dir][1];
// Change direction
dir = (dir + 1) % 4;
// Step forward to next position
row += dirs[dir][0];
col += dirs[dir][1];
}
return ans;
}