https://leetcode-cn.com/problems/spiral-matrix-ii/
很简单的一道题,不用解释过多的东西,只要控制好遍历的边界问题就好,心中有数做啥都不怕
class Solution { public int[][] generateMatrix(int n) { if(n == 0){ return new int[0][0]; } int[][] res = new int[n][n]; int max = n*n; int count = 1; int pos = 0; //当数填到n的平方的时候结束 while(count <= max){ //开始填左上到右上的列,pos用于控制每一圈的大小 for(int i = pos; i <= n-1-pos;i++){ res[pos][i] = count; count++; } //开始填从右上到右下的行 for (int i = pos+1;i <= n -pos-1;i++){ res[i][n-pos-1] = count; count++; } //开始填右下到坐下的列 for (int i = n-2-pos;i>=pos;i--){ res[n-pos-1][i] = count; count++; } //开始填左下到左上-1的行 for (int i = n-2-pos;i > pos;i--){ res[i][pos] = count; count++; } //控制当前的圈数最终填写的地方 pos++; } return res; } }