Skip to content

Instantly share code, notes, and snippets.

@gooooloo
Last active January 29, 2020 10:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gooooloo/95c5280cad093148fd60da9f1fe0c19a to your computer and use it in GitHub Desktop.
Save gooooloo/95c5280cad093148fd60da9f1fe0c19a to your computer and use it in GitHub Desktop.
打印螺旋矩阵
def main(n):
delta = [(1,0), (0,1), (-1,0), (0,-1)]
arr = [[0 for _ in range(n)] for _ in range(n)]
row,col,k,di = -1,0,1,0
while k <= n*n:
row += delta[di][0]
col += delta[di][1]
if not 0 <= row < n or not 0 <= col < n or arr[row][col] > 0:
row -= delta[di][0]
col -= delta[di][1]
di = (di + 1) % len(delta)
row += delta[di][0]
col += delta[di][1]
arr[row][col] = k
k += 1
for row in arr:
print(' '.join(f"{x}" for x in row))
def main2(n):
a = [[0 for _ in range(n)] for _ in range(n)]
dir = ((0, 1), (1, 0), (0, -1), (-1, 0))
r, c = 0, 0
i = 0
k = 1
while k <= n*n:
if a[r][c] == 0:
a[r][c] = k
k += 1
nr = r + dir[i][0]
nc = c + dir[i][1]
if 0 <= nr < n and 0 <= nc < n and a[nr][nc] == 0:
r, c = nr, nc
else:
i = (i+1) % 4
for r in a:
print(r)
if __name__ == '__main__':
main(9)
main2(9)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment