北京网站建设排名浩森宇特/武汉网站制作
螺旋矩阵II
题目描述:
给你一个正整数 n ,生成一个包含 1 到 n^2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。提示:1 <= n <= 20
题目链接
示例
class Solution {private int[][] result;public int[][] generateMatrix(int n) {// 初始化this.result = new int[n][n];fill(0,n,1);return this.result;}/*** 第一个参数为开始填充位置* 第二个参数为当前矩阵的边长* 第三个参数为带填充的数**/private void fill(int begin,int edge,int num){// 向右边遍历for(int i = 0 ; i<edge ; i++){result[begin][i+begin] = num++;}if(edge == 1) return;// 向下边遍历for(int i = 1 ; i<edge ; i++){result[begin+i][begin+edge-1] = num++;}if(edge == 1) return;// 向左边遍历for(int i = 1 ; i<edge ; i++){result[begin+edge-1][begin+edge-i-1] = num++;}if(edge == 2) return;// 向上边遍历for(int i = 1 ; i<edge-1 ; i++){result[begin+edge-1-i][begin] = num++;}if(edge>2) fill(begin+1,edge-2,num);}
}
该题和这题的解法很类似,我们只要需要将原先的添加元素操作代码修改为填充操作即可。