54. Spiral Matrix
题目
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].
思路
通过一层层遍历四边来遍历整个矩阵,由于不知道最后结束时会处在遍历哪条边的阶段,所以每次遍历完边之后判断一下行或宽的最大最小值是否合理。
代码
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> result;
if (matrix.empty()) {
return result;
}
int columnMax = matrix[0].size() - 1;
int rowMax = matrix.size() - 1;
int rowMin = 0;
int columnMin = 0;
while (true) {
for (int j = columnMin; j <= columnMax; j++) {
result.push_back(matrix[rowMin][j]);
}
rowMin++;
if (rowMin > rowMax) {
break;
}
for (int i = rowMin; i <= rowMax; i++) {
result.push_back(matrix[i][columnMax]);
}
columnMax--;
if (columnMax < columnMin) {
break;
}
for (int j = columnMax; j >= columnMin; j--) {
result.push_back(matrix[rowMax][j]);
}
rowMax--;
if (rowMax < rowMin) {
break;
}
for (int i = rowMax; i >= rowMin; i--) {
result.push_back(matrix[i][columnMin]);
}
columnMin++;
if (columnMin > columnMax) {
break;
}
}
return result;
}
};
59. Spiral Matrix II
题目
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
思路
通过一层层遍历四边来遍历整个矩阵,给每个位置赋值。
代码
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> result(n, vector<int>(n));
int count = 1;
int rMin = 0;
int rMax = n-1;
int cMin = 0;
int cMax = n-1;
while (true) {
for (int j = cMin; j <= cMax; j++) {
result[rMin][j] = count;
count++;
}
rMin++;
if (rMax < rMin) {
break;
}
for (int i = rMin; i <= rMax; i++) {
result[i][cMax] = count;
count++;
}
cMax--;
if (cMax < cMin) {
break;
}
for (int j = cMax; j >= cMin; j--) {
result[rMax][j] = count;
count++;
}
rMax--;
if (rMax < rMin) {
break;
}
for (int i = rMax; i >= rMin; i--) {
result[i][cMin] = count;
count++;
}
cMin++;
if (cMax < cMin) {
break;
}
}
return result;
}
};