题目:
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]
描述:
给出一个二维数据,按螺旋形(顺时针)方向排列元素
分析:
考察基础的数组操作,下标控制好即可
代码:(时间和空间复杂度均为 O(n * m)),其中n,m分别为二维数据的行和列)
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> result;
int n = matrix.size();
if (!n) {
return result;
}
vector<vector<bool>> visit;
initVisit(matrix, visit);
int m = matrix[0].size(), cnt = n * m, i = 0, j = 0;
while (cnt) {
while (j < m && !visit[i][j]) {
result.push_back(matrix[i][j]);
visit[i][j ++] = true;
-- cnt;
}
-- j, ++ i;
while (i < n && !visit[i][j]) {
result.push_back(matrix[i][j]);
visit[i ++][j] = true;
-- cnt;
}
-- i, -- j;
while (j >= 0 && !visit[i][j]) {
result.push_back(matrix[i][j]);
visit[i][j --] = true;
-- cnt;
}
++ j, -- i;
while (i >= 0 && !visit[i][j]) {
result.push_back(matrix[i][j]);
visit[i --][j] = true;
-- cnt;
}
++ i, ++ j;
}
return result;
}
void initVisit(vector<vector<int>>& matrix, vector<vector<bool>>& visit) {
int row = matrix.size(), column = matrix[0].size();
for (int i = 0; i < row; ++ i) {
vector<bool> temp;
for (int j = 0; j < column; ++ j) {
temp.push_back(false);
}
visit.push_back(temp);
}
}
};