一、题目描述
给你一个正整数 n
,生成一个包含 1
到 n^2
所有元素,且元素按顺时针顺序螺旋排列的 n x n
正方形矩阵 matrix
。
二、解题思路
先参考我的96_螺旋矩阵
方案一的代码,直接改改就可以了。
三、代码演示
方案一:直接模拟
class Solution {
public int[][] generateMatrix(int n) {
//使用2*4的数组:往右,往下,往左,往上,0表示不变,1是加1,-1是减1
int[][] dirs = {{0,1},{1,0},{0,-1},{-1,0}};
int row = 0, col = 0;
//使用一个变量来控制方向,默认往右走
int di = 0;
//存放结果
int[][] res = new int[n][n];
//使用一个boolean来判断某个元素是否被访问
boolean[][] seen = new boolean[n][n];
for (int i=0; i<n*n; i++){
//将值放到数组中
res[row][col] = i+1;
seen[row][col] = true; //表示某个元素被访问
//dirs是一个2行4列的数组,dirs[di][0]表示取出dirs中第di行的第1个元素
int nextRow = row + dirs[di][0]; //表示行的变化
int nextCol = col + dirs[di][1]; //表示列的变化
if (nextRow<0 || nextRow>=n || nextCol<0 || nextCol>=n || seen[nextRow][nextCol]){
//改变方向,四个方向,di表示0,1,2,3,dirs的四行
di = (di+1)%4;
}
//更新初始行列
row = row + dirs[di][0];
col = col + dirs[di][1];
}
return res;
}
}
方案二:按层模拟
class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int startRow = 0, endRow = n - 1;
int startCol = 0, endCol = n - 1;
int i = 1;
while (startRow <= endRow && startCol <= endCol) {
// top 行
for (int col = startCol; col <= endCol; col++){
res[startRow][col] = i++;
}
// right 列
for (int row = startRow + 1; row <= endRow; row++){
res[row][endCol] = i++;
}
if (startRow < endRow && startCol < endCol) {
// bottom 行
for (int col = endCol - 1; col > startCol; col--) res[endRow][col] = i++;
// left 列
for (int row = endRow; row > startRow; row--) res[row][startCol] = i++;
}
startRow++;
endRow--;
startCol++;
endCol--;
}
return res;
}
}