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的想法一样。只是把right,bottom换成n-1。不是很清楚if条件是不是需要。我觉得是需要的,不同的n终止的地方不一样。。。
public class Solution { public int[][] generateMatrix(int n) { int[][] matrix=new int[n][n]; int total=n*n; int left=0,top=0,right=n-1,bottom=n-1; int number=1; while(number<=total) { for(int i=left;i<=right;i++) { matrix[top][i]=number; number++; } top++; if(top>bottom) { break; } for(int j=top;j<=bottom;j++) { matrix[j][right]=number; number++; } right--; if(right<left) { break; } for(int k=right;k>=left;k--) { matrix[bottom][k]=number; number++; } bottom--; if(bottom<top) { break; } for(int m=bottom;m>=top;m--) { matrix[m][left]=number; number++; } left++; } return matrix; } }