Color one layer each time and recursively on the rest.

```
1 2 3
8 X 4
7 6 5
```

is colored in the order of `1 2`

, `3 4`

, `5 6`

, `7 8`

.

Four directions have the same logic.

```
import operator
class Solution:
# @return a list of lists of integer
def dfs(self, layer):
length = self.n - layer * 2
if not length:
return
if length == 1:
self.ans[layer][layer] = self.now_index
else:
now_x, now_y = layer, layer
for direction in self.directions:
for _ in range(length - 1):
self.ans[now_x][now_y] = self.now_index
now_x, now_y = tuple(map(operator.add, (now_x, now_y), direction))
self.now_index += 1
self.dfs(layer + 1)
def generateMatrix(self, n):
self.n = n
self.ans = [[0] * n for i in range(n)]
self.directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
self.now_index = 1
self.dfs(0)
return self.ans
```