问题
给定一个正整数 n,生成一个包含 1 到 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵
示例:
输入: 3
输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
思路
对于每层,从左上方开始以顺时针的顺序填入所有元素。假设当前层的左上角位于,右下角位于
,按照如下顺序填入当前层的元素:
从左到右填入上侧元素,依次为到
;
从上到下填入右侧元素,依次为到
;
如果且
,则从右到左填入下侧元素,依次为
到
,以及从下到上填入左侧元素,依次为
到
填完当前层的元素之后,将和
分别增加
,将
和
分别减少
,进入下一层继续填入元素,直到填完所有元素为止
方法一
class Solution {
public int[][] generateMatrix(int n) {
int num = 1;
int[][] matrix = new int[n][n];
int left = 0, right = n - 1, top = 0, bottom = n - 1;
while (left <= right && top <= bottom) {
for (int column = left; column <= right; column++) {
matrix[top][column] = num;
num++;
}
for (int row = top + 1; row <= bottom; row++) {
matrix[row][right] = num;
num++;
}
if (left < right && top < bottom) {
for (int column = right - 1; column > left; column--) {
matrix[bottom][column] = num;
num++;
}
for (int row = bottom; row > top; row--) {
matrix[row][left] = num;
num++;
}
}
left++;
right--;
top++;
bottom--;
}
return matrix;
}
}
- 时间复杂度:O(n^2)
- 空间复杂度:O(1)。除了返回的矩阵以外,空间复杂度是常数
方法二
思路
边界条件很多,每画一条边都要坚持一致的左闭右开或者左开右闭原则
package leetcode;
import java.util.Arrays;
public class leetcode_59_1 {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int up = 0, down = n - 1, left = 0, right = n - 1, index = 1;
while(index <= n * n){
for(int i = left; i <= right; i++){
res[up][i] = index++;
}
up++;
for(int i = up; i <= down; i++){
res[i][right] = index++;
}
right--;
for(int i = right; i >= left; i--){
res[down][i] = index++;
}
down--;
for(int i = down; i >= up; i--){
res[i][left] = index++;
}
left++;
}
return res;
}
public static void main(String[] args){
leetcode_59_1 lt = new leetcode_59_1();
int[][] res = lt.generateMatrix(3);
System.out.println(Arrays.deepToString(res));
}
}
——打印多维数组