Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
public class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int x0 = 0, x1 = n - 1, y0 = 0, y1 = n - 1;
int ele = 0;
while (x0 <= x1 && y0 <= y1) {
for (int i = y0; i <= y1; i++) {
res[x0][i] = ++ele;
}
for (int i = x0 +1; i <= x1; i++) {
res[i][y1] = ++ele;
}
if (x0 == x1) break;
for (int i = y1 - 1; i >= y0; i--) {
res[x1][i] = ++ele;
}
if (y0 == y1) break;
for (int i = x1 - 1; i > x0; i--) {
res[i][y0] = ++ele;
}
x0++; x1--; y0++; y1--;
}
return res;
}
}