题目描述
给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
示例
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
思路
其实就是顺时针方向填入数组元素。
首先需要确定四个方向:右下左上。右:从1到3,下:从3到5,左:从5到7,上:从7到8,依次类推。
右方向的行数不变,列数每次加1;
下方向的列数不变,行数每次加1;
左方向的行数不变,列数每次减1;
上方向的列数不变,行数每次减1。
因此可以定义一个代表方向的二维数组direction[[0,1],[1,0],[0,-1],[-1,0]],每向数组中填入一个数后,就判断一次是否到达边界,如果到达边界,就转换一次方向。
代码
public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
int num = 1;
int row = 0;
int column = 0;
int maxNum = n * n;
int directionIndex = 0;
//代表右下左上四个方向
int[][] direction = {{0,1},{1,0},{0,-1},{-1,0}};
while (num <= maxNum) {
matrix[row][column] = num;
num++;
//判断下一个位置是否到达边界
int nextRow = row + direction[directionIndex][0];
int nextColumn = column + direction[directionIndex][1];
if (nextColumn >= n || nextRow >= n || matrix[nextRow][nextColumn] != 0 || nextRow < 0 || nextColumn < 0) {
//到达边界,切换到下一个方向
directionIndex = (directionIndex + 1) % 4;
}
row = row + direction[directionIndex][0];
column = column + direction[directionIndex][1];
}
return matrix;
}