very similar question , just inserting into the matrix instead of traversaling it.
class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
// define the boundry
int up = 0;
int down = n - 1;
int left = 0;
int right = n - 1;
int curr = 1; // we starting inserting one
while(curr <= n * n){
// we have more stuff to insert
// first we want to insert from left to right
for(int i = left; i <= right; i ++){
res[up][i] = curr ++;
}
// now we want to insert downwards
for(int j = up + 1; j <= down; j ++){
res[j][right] = curr;
curr ++;
}
// now if we are not on the same row we would wanna go cross left
if(up != down){
for(int i = right - 1; i >= left; i --){
res[down][i] = curr++;
}
}
// now finally we want to go down to up
if(left != right){
for(int j = down - 1; j > up; j --){
res[j][left] = curr ++;
}
}
// shrink the boundry
left ++;
right --;
up ++;
down --;
}
return res;
}
}
