Skip to content

Commit

Permalink
Merge pull request youngyangyang04#2426 from wulin-no2/lina_branch
Browse files Browse the repository at this point in the history
按照解题思路优化代码及变量名称
  • Loading branch information
youngyangyang04 authored Feb 6, 2024
2 parents 611336a + 671714f commit 216b9d7
Showing 1 changed file with 34 additions and 25 deletions.
59 changes: 34 additions & 25 deletions problems/0059.螺旋矩阵II.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,42 +138,51 @@ public:
```Java
class Solution {
public int[][] generateMatrix(int n) {
int loop = 0; // 控制循环次数
int[][] res = new int[n][n];
int start = 0; // 每次循环的开始点(start, start)
int count = 1; // 定义填充数字
int i, j;

while (loop++ < n / 2) { // 判断边界后,loop从1开始
// 模拟上侧从左到右
for (j = start; j < n - loop; j++) {
res[start][j] = count++;
int[][] nums = new int[n][n];
int startX = 0, startY = 0; // 每一圈的起始点
int offset = 1;
int count = 1; // 矩阵中需要填写的数字
int loop = 1; // 记录当前的圈数
int i, j; // j 代表列, i 代表行;

while (loop <= n / 2) {

// 顶部
// 左闭右开,所以判断循环结束时, j 不能等于 n - offset
for (j = startY; j < n - offset; j++) {
nums[startX][j] = count++;
}

// 模拟右侧从上到下
for (i = start; i < n - loop; i++) {
res[i][j] = count++;
// 右列
// 左闭右开,所以判断循环结束时, i 不能等于 n - offset
for (i = startX; i < n - offset; i++) {
nums[i][j] = count++;
}

// 模拟下侧从右到左
for (; j >= loop; j--) {
res[i][j] = count++;
// 底部
// 左闭右开,所以判断循环结束时, j != startY
for (; j > startY; j--) {
nums[i][j] = count++;
}

// 模拟左侧从下到上
for (; i >= loop; i--) {
res[i][j] = count++;
// 左列
// 左闭右开,所以判断循环结束时, i != startX
for (; i > startX; i--) {
nums[i][j] = count++;
}
start++;
startX++;
startY++;
offset++;
loop++;
}

if (n % 2 == 1) {
res[start][start] = count;
if (n % 2 == 1) { // n 为奇数时,单独处理矩阵中心的值
nums[startX][startY] = count;
}

return res;
return nums;
}
}


```

### python3:
Expand Down

0 comments on commit 216b9d7

Please sign in to comment.