Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

更新0059.螺旋矩阵II的C#版本保证与C++版本的代码保持一致性 #2860

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 57 additions & 18 deletions problems/0059.螺旋矩阵II.md
Original file line number Diff line number Diff line change
Expand Up @@ -715,26 +715,65 @@ object Solution {
### C#:

```csharp
public class Solution {
public int[][] GenerateMatrix(int n) {
int[][] answer = new int[n][];
for(int i = 0; i < n; i++)
answer[i] = new int[n];
int start = 0;
int end = n - 1;
int tmp = 1;
while(tmp < n * n)
public int[][] GenerateMatrix(int n)
{
// 参考Carl的代码随想录里面C++的思路
// https://www.programmercarl.com/0059.%E8%9E%BA%E6%97%8B%E7%9F%A9%E9%98%B5II.html#%E6%80%9D%E8%B7%AF
int startX = 0, startY = 0; // 定义每循环一个圈的起始位置
int loop = n / 2; // 每个圈循环几次,例如n为奇数3,那么loop = 1 只是循环一圈,矩阵中间的值需要单独处理
int count = 1; // 用来给矩阵每个空格赋值
int mid = n / 2; // 矩阵中间的位置,例如:n为3, 中间的位置就是(1,1),n为5,中间位置为(2, 2)
int offset = 1;// 需要控制每一条边遍历的长度,每次循环右边界收缩一位

// 构建result二维数组
int[][] result = new int[n][];
for (int k = 0; k < n; k++)
{
result[k] = new int[n];
}

int i = 0, j = 0; // [i,j]
while (loop > 0)
{
i = startX;
j = startY;
// 四个For循环模拟转一圈
// 第一排,从左往右遍历,不取最右侧的值(左闭右开)
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--)
{
for(int i = start; i < end; i++) answer[start][i] = tmp++;
for(int i = start; i < end; i++) answer[i][end] = tmp++;
for(int i = end; i > start; i--) answer[end][i] = tmp++;
for(int i = end; i > start; i--) answer[i][start] = tmp++;
start++;
end--;
}
if(n % 2 == 1) answer[n / 2][n / 2] = tmp;
return answer;
result[i][j] = count++;
}
// 第二圈开始的时候,起始位置要各自加1, 例如:第一圈起始位置是(0, 0),第二圈起始位置是(1, 1)
startX++;
startY++;

// offset 控制每一圈里每一条边遍历的长度
offset++;
loop--;
}
if (n % 2 == 1)
{
// n 为奇数
result[mid][mid] = count;
}
return result;
}
```

Expand Down