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 ] ]
public class Solution { public int[][] generateMatrix(int n) { int[][] a = new int[n][n]; if(n == 0) return a; if(n == 1) { a[0][0] = 1; return a; } int top = 0; int bottom = n -1; int left = 0; int right = n - 1; int num = 1; while(top <= bottom && left <= right){ //right to left in top for(int i = left ; i <= right ; i++){ a[top][i] = num; num++; } top++; //top to bottom in right for(int i = top ; i <= bottom ; i++){ a[i][right] = num; num++; } right--; // right -> left in bottom if(bottom >= top){ for(int i = right ; i >= left ; i--){ a[bottom][i] = num; num++; } bottom--; } //bottom -> top in left if(right >= left){ for(int i = bottom ; i >= top ; i--){ a[i][left] = num; num++; } left++; } } return a; } }