# My simple Java solution and explanation

• ``````public class Solution {
public int[][] generateMatrix(int n) {
int dir = 0;
int[] dx = new int[]{0, 1, 0, -1};
int[] dy = new int[]{1, 0, -1, 0};

int[][] ret = new int[n][n];
int[][] mp = new int[n][n];
int cnt = 0;

int x = 0;
int y = 0;
while(cnt < n * n){
ret[x][y] = ++cnt;
if(x + dx[dir] >= n || x + dx[dir] < 0 ||
y + dy[dir] >= n || y + dy[dir] < 0 ||
mp[x + dx[dir]][y + dy[dir]] == 1){
dir = (dir + 1) % 4;
}
mp[x][y] = 1;
x += dx[dir];
y += dy[dir];

}
return ret;
}
}
``````

Firstly, we know that there are n * n elements exactly. So , we begin from left-top , that is `(0,0)`. We define 4 directions in the order `right`,`down`,`left`,`top`, which is the rule the numbers generated. Then, we generate the number one by one. If the position which the next number will be at is not allowed or there was already a number here, we change the direction to the next value using `dx[]`, `dy[]`. Finally, when we get n * n elements, break.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.