The idea is straightforward. I have defined four variables and four directions.

**Variables**

top(t) - the index for the topmost row of the matrix (initially zero)

bottom(b) - the index for the bottom most row of the matrix (initially n-1)

left(l) - the index for the leftmost column of the matrix (initially 0)

right(r) - the index for the rightmost column of the matrix( (initially n-1)

**Directions**

1 -> LEFT TO RIGHT

2 -> TOP TO DOWN

3 -> RIGHT TO LEFT

4 -> BOTTOM TO UP

I start from Direction 1 and each time I complete a direction I inc/decrement the t,b,l,r indexes accordingly to mark the rows/columns that are complete.

Direction 1 - top row complete, increment t by 1;

Direction 2 - right most column complete, decrement r by 1;

Direction 3 - bottom most row complete, decrement b by 1;

Direction 4 - left most column complete, increment l by 1;

I keep doing this until there are no more locations in the matrix.

```
public class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int t = 0;
int b = n-1;
int l = 0;
int r = n-1;
int direction = 1;
int currentNum = 1;
while ( (t<=b) && (l<=r) ) {
if (direction == 1) {
for (int i=l;i<=r;i++) {
res[t][i] = currentNum++;
}
direction = 2;
t++;
} else if (direction == 2) {
for (int i=t;i<=b;i++) {
res[i][r] = currentNum++;
}
direction = 3;
r--;
} else if (direction == 3) {
for (int i=r;i>=l;i--) {
res[b][i] = currentNum++;
}
direction = 4;
b--;
} else if (direction == 4) {
for (int i=b;i>=t;i--) {
res[i][l] = currentNum++;
}
direction = 1;
l++;
}
}
return res;
}
}
```