Created
May 13, 2019 07:43
-
-
Save Azureki/fe48ee197bc69ab1aac0fa3e95ff212a to your computer and use it in GitHub Desktop.
顺时针 逆时针 矩阵
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| n = 5 | |
| dirs = [(0, -1), (1, 0), (0, 1), (-1, 0)] | |
| visited = [[False] * n for i in range(n)] | |
| res = [[0] * n for i in range(n)] | |
| def dfs(pos, tem, d): | |
| x, y = pos | |
| while True: | |
| res[x][y] = tem | |
| visited[x][y] = True | |
| tem += 1 | |
| yield None | |
| x, y = x + dirs[d][0], y + dirs[d][1] | |
| if 0 <= x < n and 0 <= y < n and not visited[x][y]: | |
| continue | |
| else: | |
| x, y = x - dirs[d][0], y - dirs[d][1] | |
| d = (d + 1) % 4 | |
| x, y = x + dirs[d][0], y + dirs[d][1] | |
| g = dfs((0, n - 1), 1, 0) | |
| for i in range(n * n): | |
| next(g) | |
| for i in range(n): | |
| print(res[i]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment