Mussab_Blue

Spiral Matrix

Jun 14th, 2024
513
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.77 KB | None | 0 0
  1.  
  2. dirs = [
  3.     (0, 1), #RIGHT
  4.     (1, 0), #DOWN
  5.     (0, -1), #LEFT
  6.     (-1, 0) #Up
  7. ]
  8.  
  9. dim = 5
  10. pos = [0, -1] #starting point
  11. target = dim**2
  12. matrix = [[0]*dim for _ in range(dim)]
  13.  
  14. def withinBorders(x, y):
  15.     px, py, = pos[0]+x, pos[1]+y
  16.     if not (0 <= px < dim): return False
  17.     if not (0 <= py < dim): return False
  18.     if isinstance(matrix[px][py], str): return False      
  19.     return True
  20.    
  21. while target:
  22.     (x, y), *dirs, = dirs
  23.     for _ in range(dim):
  24.         if not withinBorders(x, y): break        
  25.        
  26.         pos[0] += x
  27.         pos[1] += y
  28.        
  29.         px, py = pos
  30.         matrix[px][py] = f'0{target}'[-2:]
  31.        
  32.         target -= 1      
  33.    
  34.     dirs = [*dirs, (x, y)]
  35.        
  36. for r in matrix:
  37.     print(*r)
  38.  
  39.  
  40.  
  41.  
Advertisement
Add Comment
Please, Sign In to add comment