1. 原题链接
https://leetcode.com/problems/spiral-matrix-ii/description/
2. 题目要求
给定一个正整数n,求出从1到n平方的螺旋矩阵。例如n为3,构成的螺旋矩阵如下图所示
3. 解题思路
该题与54题Spiral Matrix的解题思路大致相同,同样是一个while循环内,确定螺旋矩阵一个圈上的所有元素。
采用一个计数器count,count初始为1,每确定一个位置上的元素,count加1,
4. 代码实现
public class SpiralMatrixII59 {
public static void main(String[] args) {
for(int []n:generateMatrix(3)){
for(int x:n)
System.out.print(x+" ");
System.out.println();
}
}
/**
* t t t t t
* l ... r
* l r
* l ... r
* b b b b r
*/
public static int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int left = 0, right = n - 1;
int top = 0, bottom = n - 1;
int count = 1;
while (left <=right) {
// 确定t所在边上的元素
for (int i = left; i <= right; i++) {
res[top][i] = count++;
}
top++;
// 确定r所在边上的元素
for (int i = top; i <= bottom; i++) {
res[i][right] = count++;
}
right--;
// 确定b所在边上的元素
for(int i= right;i>=left;i--){
res[bottom][i]=count++;
}
bottom--;
// 确定l所在边上的元素
for(int i =bottom;i>=top;i--){
res[i][left]=count++;
}
left++;
}
return res;
}
}