Problem:
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 ] ]
Solution:
code
public class Solution {
public int[][] generateMatrix(int n) {
int[][] array = new int[n][n];
int a = 0;
int b = n - 1;
int c = 0;
int d = n - 1;
int count = 0;
while (a <= b && c <= d) {
if (a <= b ) {
for (int i = c; i <= d; i++) {
count++;
array[a][i] = count;
}
a++;
}
if (c <= d) {
for (int i = a; i <= b; i++) {
count++;
array[i][d] = count;
}
d--;
}
if (a <= b) {
for (int i = d; i >= c; i--) {
count++;
array[b][i] = count;
}
b--;
}
if (c <= d) {
for (int i = b ; i >= a; i--) {
count++;
array[i][c] = count;
}
c++;
}
}
return array;
}
}