今天刷的题是LeetCode第59题,https://leetcode-cn.com/problems/spiral-matrix-ii/,该题的要求是:
给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。比如:
输入: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
这个代码也很好写,我用的就是简单的while循环,具体地如下:
public class GenerateMatrix_59_middle { public static void main(String[] args) { generate(5); } public static int[][] generate(int n){ int[][] result=new int[n][n];//输出最后的结果 boolean[][] hasNumber=new boolean[n][n];//判断这个位置上是否已经有的元素 int i=1; int x=0; int y=0; while (i<=n*n){ if (hasNumber[x][y]==false){ result[x][y]=i; hasNumber[x][y]=true; i++; }else { if (y+1<n&&hasNumber[x][y+1]==false)y=y+1; else if (x+1<n&&hasNumber[x][y+1]==false)x=x+1; else if (y-1>=0&&hasNumber[x][y+1]==false)y=y-1; else if (x-1>=0&&hasNumber[x][y+1]==false)x=x-1; result[x][y]=i; hasNumber[x][y]=true; i++; } while (y+1<n&&hasNumber[x][y+1]==false){ y=y+1; result[x][y]=i; hasNumber[x][y]=true; i++; } while (x+1<n&&hasNumber[x+1][y]==false){ x=x+1; result[x][y]=i; hasNumber[x][y]=true; i++; } while (y-1>=0&&hasNumber[x][y-1]==false){ y=y-1; result[x][y]=i; hasNumber[x][y]=true; i++; } while (x-1>=0&&hasNumber[x-1][y]==false){ x=x-1; result[x][y]=i; hasNumber[x][y]=true; i++; } } for (int j = 0; j <n ; j++) { for (int k = 0; k <n ; k++) { System.out.print(result[j][k]+"---"); } System.out.println(); } return result; } }