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 螺旋矩阵的基础上。只要会做spiral matrix 螺旋矩阵,那么这一题也就简单了。spiral matrix 螺旋矩阵是遍历并输出元素,需要判断以防止重复输出。
而这题是添加元素,不需要判断,只需遍历,然后将n^2个元素填完就可以了。
class Solution { public int[][] generateMatrix(int n) { int[][] res=new int[n][n]; if(n==0) return res; int rowStart=0; int rowEnd=n-1; int colStart=0; int colEnd=n-1; int index=1; while(index<=(n*n)){ for(int j=colStart;j<=colEnd&&index<=(n*n);j++) res[rowStart][j]=index++; rowStart++; for(int i=rowStart;i<=rowEnd&&index<=(n*n);i++) res[i][colEnd]=index++; colEnd--; for(int j=colEnd;j>=colStart&&index<=(n*n);j--) res[rowEnd][j]=index++; rowEnd--; for(int i=rowEnd;i>=rowStart&&index<=(n*n);i--) res[i][colStart]=index++; colStart++; } return res; } }