Problem Description:
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
Analysis:
Set four directions and steps that each traverse should walk.
The initial steps are n for horizontal and m - 1 for vertical.
initial position is (0, -1);
vector<int> spiralOrder(vector<vector<int>>& matrix)
{
int m = matrix.size();
int n = m ? matrix[0].size() : 0;
int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
vector<int> res;
// vector<vector<int> > dirs {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int steps[2] = {n, m - 1};//steps can work
int iDir = 0; //index of direction
int ir = 0, ic = -1; // initial position
while (steps[iDir % 2])
{
for (int i = 0; i < steps[iDir % 2]; ++i)
{
ir += dirs[iDir][0];
ic += dirs[iDir][1];
res.push_back(matrix[ir][ic]);
}
steps[iDir % 2]--;
iDir = (iDir + 1) % 4;
}
return res;
}
Another neat solution from this link
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.empty()) return {};
int m = matrix.size(), n = matrix[0].size();
vector<int> spiral(m * n);
int u = 0, d = m - 1, l = 0, r = n - 1, k = 0;
while (true) {
// up
for (int col = l; col <= r; col++) spiral[k++] = matrix[u][col];
if (++u > d) break;
// right
for (int row = u; row <= d; row++) spiral[k++] = matrix[row][r];
if (--r < l) break;
// down
for (int col = r; col >= l; col--) spiral[k++] = matrix[d][col];
if (--d < u) break;
// left
for (int row = d; row >= u; row--) spiral[k++] = matrix[row][l];
if (++l > r) break;
}
return spiral;
}
Follow up:
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
class Solution {
public:
vector<vector<int> > generateMatrix(int n)
{
int r1 = 0, r2 = n - 1, c1 = 0, c2 = n - 1;
int num = 1;
vector<vector<int> > res(n, vector<int>(n));
while (true)
{
for (int col = c1; col <= c2; col++) res[r1][col] = num++;
if (++r1 > r2) break;
for (int row = r1; row <= r2; row++) res[row][c2] = num++;
if (--c2 < c1) break;
for (int col = c2; col >= c1; col--) res[r2][col] = num++;
if (--r2 < r1) break;
for (int row = r2; row >= r1; row--) res[row][c1] = num++;
if (c1++ > c2) break;
}
return res;
}
};