Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from pprint import pprint
- def can_go_right(M, r, c, size):
- if c+2 < size:
- if M[r][c+2] == 1:
- return False
- if c+1 < size and r+1 < size:
- if M[r][c+1] == 0 and M[r+1][c+1] == 0:
- return True
- return False
- def can_go_left(M, r, c, size):
- if c-2 > -1:
- if M[r][c-2] == 1:
- return False
- if c-1 > -1 and r-1 > -1:
- if M[r][c-1] == 0 and M[r-1][c-1] == 0:
- return True
- return False
- def can_go_up(M, r, c, size):
- if r-2 > -1:
- if M[r-2][c] == 1:
- return False
- if r-1 > -1:
- if M[r-1][c] == 0:
- return True
- return False
- def can_go_down(M, r, c, size):
- if r+2 < size:
- if M[r+2][c] == 1:
- return False
- if r+1 < size:
- if M[r+1][c] == 0:
- return True
- return False
- def spiralize(size):
- r = c = 0
- tries = 0
- M = [[0]*size for _ in range(size)]
- M[r][c] = 1
- while tries < 2:
- while can_go_right(M, r, c, size):
- tries = 0
- c += 1
- M[r][c] = 1
- else:
- tries += 1
- while can_go_down(M, r, c, size):
- tries = 0
- r += 1
- M[r][c] = 1
- else:
- tries += 1
- while can_go_left(M, r, c, size):
- tries = 0
- c -= 1
- M[r][c] = 1
- else:
- tries += 1
- while can_go_up(M, r, c, size):
- tries = 0
- r -= 1
- M[r][c] = 1
- else:
- tries += 1
- return M
- if __name__ == "__main__":
- res = spiralize(8)
- pprint(res)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement