给你一个正整数?n ,生成一个包含 1 到?n2?所有元素,且元素按顺时针顺序螺旋排列的?n x n 正方形矩阵 matrix 。
示例 1:
输入:n = 3 输出:[[1,2,3],[8,9,4],[7,6,5]]
思路其实和我写的 54.螺旋矩阵?是一致的,到了临界点转向就行了,因此直接贴代码和结果:
public static final int RIGHT = 1;
public static final int DOWN = 2;
public static final int LEFT = 3;
public static final int UP = 4;
private int[][] result;
public int[][] generateMatrix(int n) {
this.result = new int[n][n];
recursion(0, 0, 1, RIGHT, n, n*n, result);
return result;
}
private static void recursion(int x, int y, int index, int direction, int width, int sum, int[][] result) {
if (index == sum+1) return;
result[x][y] = index;
switch (direction) {
case RIGHT:
if (y+1 == width || result[x][y+1] != 0) {
direction = DOWN;
++ x;
} else {
++ y;
}
break;
case DOWN:
if (x+1 == width || result[x+1][y] != 0) {
direction = LEFT;
-- y;
} else {
++ x;
}
break;
case LEFT:
if (y-1 == -1 || result[x][y-1] != 0) {
direction = UP;
-- x;
} else {
-- y;
}
break;
case UP:
if (x-1 == -1 || result[x-1][y] != 0) {
direction = RIGHT;
++ y;
} else {
-- x;
}
break;
}
recursion(x, y, index+1, direction, width, sum, result);
}
????????????????
?时间复杂度 O(N) 额外空间复杂度 O(1)
|