Advertisement
lavrent

spiral_matrix

Jul 10th, 2022
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.68 KB | None | 0 0
  1. rows, cols = map(int, input().split())
  2.  
  3. mtrx = [[0 for _ in range(cols)] for __ in range(rows)]
  4. mtrx[0][0] = 1
  5. ro, co = 0, 1
  6. row, col = 0, 0
  7. for n in range(2, cols * rows + 1):
  8.     if 0 <= row + ro < rows and 0 <= col + co < cols \
  9.             and mtrx[row + ro][col + co] == 0:
  10.         row += ro
  11.         col += co
  12.         mtrx[row][col] = n
  13.         continue
  14.  
  15.     if ro and (not 0 <= row + ro < rows or mtrx[row + ro][col]):
  16.         co = -1 if ro == 1 else 1
  17.         ro = 0
  18.  
  19.     if co and (not 0 <= col + co < cols or mtrx[row][col + co]):
  20.         ro = 1 if co == 1 else -1
  21.         co = 0
  22.     row += ro
  23.     col += co
  24.     mtrx[row][col] = n
  25.  
  26. for row in mtrx:
  27.     print(*row)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement