【题目】
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 ] ]
【分析】
1.与上一题的思路类似,按四个方向分别填充数组
【算法实现】
public class Solution { public int[][] generateMatrix(int n) { int[][] res=new int[n][n]; int x1=0; int y1=0; int x2=n-1; int y2=n-1; int flag=1; while(x1<=x2&&y1<=y2) { for(int i=y1;i<=y2;i++) res[x1][i]=flag++; for(int i=x1+1;i<=x2;i++) res[i][y2]=flag++; if(x1!=x2) for(int i=y2-1;i>=y1;i--) res[x2][i]=flag++; if(y1!=y2) for(int i=x2-1;i>x1;i--) res[i][y1]=flag++; x1++; y1++; x2--; y2--; } return res; } }