Advertisement
Guest User

Untitled

a guest
Feb 20th, 2020
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.67 KB | None | 0 0
  1. from pprint import pprint
  2.  
  3.  
  4. def can_go_right(M, r, c, size):
  5.     if c+2 < size:
  6.         if M[r][c+2] == 1:
  7.             return False
  8.     if c+1 < size and r+1 < size:
  9.         if M[r][c+1] == 0 and M[r+1][c+1] == 0:
  10.             return True
  11.     return False
  12.  
  13. def can_go_left(M, r, c, size):
  14.     if c-2 > -1:
  15.         if M[r][c-2] == 1:
  16.             return False
  17.     if c-1 > -1 and r-1 > -1:
  18.         if M[r][c-1] == 0 and M[r-1][c-1] == 0:
  19.             return True
  20.     return False
  21.  
  22. def can_go_up(M, r, c, size):
  23.     if r-2 > -1:
  24.         if M[r-2][c] == 1:
  25.             return False
  26.     if r-1 > -1:
  27.         if M[r-1][c] == 0:
  28.             return True
  29.     return False
  30.  
  31. def can_go_down(M, r, c, size):
  32.     if r+2 < size:
  33.         if M[r+2][c] == 1:
  34.             return False
  35.     if r+1 < size:
  36.         if M[r+1][c] == 0:
  37.             return True
  38.     return False
  39.    
  40. def spiralize(size):
  41.     r = c = 0
  42.     tries = 0
  43.     M = [[0]*size for _ in range(size)]
  44.     M[r][c] = 1
  45.     while tries < 2:
  46.         while can_go_right(M, r, c, size):
  47.             tries = 0
  48.             c += 1
  49.             M[r][c] = 1
  50.         else:
  51.             tries += 1
  52.         while can_go_down(M, r, c, size):
  53.             tries = 0
  54.             r += 1
  55.             M[r][c] = 1
  56.         else:
  57.             tries += 1
  58.         while can_go_left(M, r, c, size):
  59.             tries = 0
  60.             c -= 1
  61.             M[r][c] = 1
  62.         else:
  63.             tries += 1
  64.         while can_go_up(M, r, c, size):
  65.             tries = 0
  66.             r -= 1
  67.             M[r][c] = 1
  68.         else:
  69.             tries += 1
  70.     return M
  71.  
  72. if __name__ == "__main__":
  73.     res = spiralize(8)
  74.     pprint(res)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement