1.方法一:
/*
思路:定义上下左右边界,模拟循环转圈,需要注意最后只剩一行或一列的时候需要添加额外的判断
因为每次都是先往右走和先往下走,所以往右走和往下走的路一定是没走过的路,不需要加 if 判断;往左走的时候,如果 top == bottom,那么会重复走之前从左往右走过的路,所以需要加上 top < bottom 的判断,同理往上走也一样。
*/
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
//if(n == 0) return {[]};
int left = 0, right = n - 1;
int top = 0, bottom = n - 1;
int count = 1;
vector<vector<int>> result(n, vector<int>(n, 0));
while(left <= right && top <= bottom){
for(int colum = left; colum <= right; colum++){
result[top][colum] = count++;
}
for(int row = top + 1; row <= bottom; row++){
result[row][right] = count++;
}
if(left < right && top < bottom){
for(int colum = right - 1; colum > left; colum--){
result[bottom][colum]= count++;
}
for(int row = bottom; row > top; row--){
result[row][left]= count++;
}
}
left++, right--;
top++, bottom--;
}
return result;
}
};
2. 方法二:
坚持循环不变量:
- 填充上行从左到右
- 填充右列从上到下
- 填充下行从右到左
- 填充左列从下到上
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> result(n, vector<int>(n,0));
int startx = 0, starty = 0;
int i, j;
int count = 1;
int offset = 1;
int loop = n /2;
int mid = n / 2;
while(loop--){
i = startx;
j = starty;
//从左到右
for(; j < n - offset; j++){
result[i][j] = count++;
}
//从上到下
for(; i < n - offset; i++){
result[i][j] = count++;
}
//从右到左
for(; j > starty; j--){
result[i][j] = count++;
}
//从下到上
for(; i > startx; i--){
result[i][j] = count++;
}
startx++;
starty++;
offset += 1;
}
if(n % 2 == 1) result[mid][mid] = count;
return result;
}
};