generat_matrix.py 690 B

12345678910111213141516171819202122232425
  1. from typing import List
  2. def generateMatrix(n: int) -> List[List[int]]:
  3. l, r, t, b = 0, n - 1, 0, n - 1
  4. mat = [[0 for _ in range(n)] for _ in range(n)]
  5. num, tar = 1, n * n
  6. while num <= tar:
  7. for i in range(l, r + 1): # left to right
  8. mat[t][i] = num
  9. num += 1
  10. t += 1
  11. for i in range(t, b + 1): # top to bottom
  12. mat[i][r] = num
  13. num += 1
  14. r -= 1
  15. for i in range(r, l - 1, -1): # right to left
  16. mat[b][i] = num
  17. num += 1
  18. b -= 1
  19. for i in range(b, t - 1, -1): # bottom to top
  20. mat[i][l] = num
  21. num += 1
  22. l += 1
  23. return mat