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[][] res = new int[n][n]; int cnt = 1; int top = 0; int bottom = n - 1; int left = 0; int right = n - 1; while (left < right && top < bottom) { for (int i = left; i < right; i++) { res[top][i] = cnt++; } for (int i = top; i < bottom; i++) { res[i][right] = cnt++; } for (int i = right; i > left; i--) { res[bottom][i] = cnt++; } for (int i = bottom; i > top; i--) { res[i][left] = cnt++; } left++; right--; top++; bottom--; } if (n % 2 != 0) { res[n/2][n/2] = cnt; } return res; } }