54题的变体,不过思路都是一样的
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n, 0));
int top = 0, bottom = n-1, left = 0, right = n-1;
int i = 1;
while(true){
for(int col = left; col <= right; ++col) res[top][col] = i++;
++top;
if(top > bottom) break;
for(int row = top; row <= bottom; ++row) res[row][right] = i++;
--right;
if(left > right) break;
for(int col = right; col >= left; --col) res[bottom][col] = i++;
--bottom;
if(top > bottom) break;
for(int row = bottom; row >= top; --row) res[row][left] = i++;
++left;
if(left > right) break;
}
return res;
}
};
或者换个写法:
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n, 0));
int top = 0, bottom = n-1, left = 0, right = n-1;
int i = 1, target = n*n;
while(i <= target){
for(int col = left; col <= right; ++col) res[top][col] = i++;
++top;//上边界下移
for(int row = top; row <= bottom; ++row) res[row][right] = i++;
--right;//右边界左移
for(int col = right; col >= left; --col) res[bottom][col] = i++;
--bottom;//右边界左移
for(int row = bottom; row >= top; --row) res[row][left] = i++;
++left;//右边界左移
}
return res;
}
};