LeetCode OJ 59. Spiral Matrix II

时间:2021-04-13 13:51:24

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:

[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

【题目分析】

与Spiral Matrix不同,这个题目要求生成一个方阵,方阵的值是螺旋递增的。


【思路】

其实这个题目与上一个大同小异,他们遍历矩阵的顺序是相同的,只要把取值变为赋值就可以了。


【java代码】

 public class Solution {
public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n]; int top = 0;
int bottom = n-1;
int left = 0;
int right = n-1;
int num = 1; while(true){
for(int i = left; i <= right; i++) matrix[top][i] = num++;
top++;
if(left > right || top > bottom) break; for(int i = top; i <= bottom; i++) matrix[i][right] = num++;
right--;
if(left > right || top > bottom) break; for(int i = right; i >= left; i--) matrix[bottom][i] = num++;
bottom--;
if(left > right || top > bottom) break; for(int i = bottom; i >= top; i--) matrix[i][left] = num++;
left++;
if(left > right || top > bottom) break;
} return matrix;
}
}