Advertisement
Guest User

Untitled

a guest
Sep 26th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. import collections
  2. import copy
  3. def slidingPuzzle(board):
  4. """
  5. :type board: List[List[int]]
  6. :rtype: int
  7. """
  8. q = collections.deque()
  9. q.append(([board], 0, [(i, j) for i in range(len(board)) for j in range(len(board[0])) if board[i][j] == 0][0]))
  10.  
  11.  
  12. #newp is a list of boards, the path
  13. #newp2 is the new path
  14. seen = set()
  15. while q:
  16. newp, d, zero = q.popleft()
  17. new = newp[-1]
  18. if tuple(new[0] + new[1]) in seen:
  19. continue
  20. seen.add(tuple(new[0] + new[1]))
  21. if new == [[1, 2, 3], [4, 5, 6], [7,8,0]]:
  22. return newp
  23. for i in range(len(new)):
  24. for j in range(len(new[0])):
  25. if (abs(i - zero[0]) == 1 and abs(j - zero[1]) == 0) or (
  26. abs(i - zero[0]) == 0 and abs(j - zero[1]) == 1):
  27. new2 = copy.deepcopy(new)
  28. new2[i][j], new2[zero[0]][zero[1]] = 0, new[i][j]
  29. newp2 = newp.copy()
  30. newp2.append(new2)
  31. q.append((newp2, d + 1, (i, j)))
  32. return -1
  33.  
  34. print(slidingPuzzle([[1,2,3],[4,5,0], [7,8,6]]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement