class Solution {
public int[][] generateMatrix(int n) {
int end = n * n;
int counter = 1;
int[][] res = new int[n][n];
boolean[][] visited = new boolean[n][n];
int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int i = 0;
int j = 0;
int directionIndex = 0;
while(counter <= end){
res[i][j] = counter;
visited[i][j] = true;
counter ++;
int nextI = i + directions[directionIndex][0];
int nextJ = j + directions[directionIndex][1];
if(nextI < 0 || nextI >= n || nextJ < 0 || nextJ >=n || visited[nextI][nextJ]){
directionIndex = (directionIndex + 1) % 4;
}
i += directions[directionIndex][0];
j += directions[directionIndex][1];
}
return res;
}
}
本题的思路和螺旋矩阵类似,通过方向数组和边界判断实现螺旋转向。
另外,不需要使用 visited 函数确定是否访问过该点,而是直接根据 res[nextI][nextJ] > 0 来判断。
本文详细介绍了如何实现一个生成螺旋矩阵的算法,通过一个二维数组和四个方向数组进行移动,同时避免了使用额外的visited数组。核心思路是利用边界判断和方向切换,实现了从1到n*n的螺旋填充。优化点在于通过检查res[nextI][nextJ]是否已填充,而不是使用visited数组。
675

被折叠的 条评论
为什么被折叠?



