Guest User

Untitled

a guest
Feb 18th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1. import queue
  2.  
  3. moves = {
  4. 0: {1, 3},
  5. 1: {0, 2, 4},
  6. 2: {1, 5},
  7. 3: {0, 4},
  8. 4: {1, 3, 5},
  9. 5: {2, 4}
  10. }
  11.  
  12. class Solution:
  13. def slidingPuzzle(self, board):
  14. """
  15. :type board: List[List[int]]
  16. :rtype: int
  17. """
  18. result = 0
  19.  
  20. _ = board[0] + board[1]
  21. s = ''.join(str(x) for x in _)
  22.  
  23. q = queue.Queue()
  24. q.put(s)
  25. q1 = queue.Queue()
  26.  
  27. m = set()
  28.  
  29. while not q.empty():
  30. x = q.get()
  31. if x == '123450':
  32. return result
  33. oz = x.find('0')
  34. for nz in moves[oz]:
  35. ns = ''
  36. for j in range(0, 6):
  37. if j == oz:
  38. ns += x[nz]
  39. elif j == nz:
  40. ns += x[oz]
  41. else:
  42. ns += x[j]
  43. if ns not in m:
  44. m.add(ns)
  45. q1.put(ns)
  46.  
  47. if q.empty():
  48. result += 1
  49. q1, q = q, q1
  50.  
  51. return -1
Add Comment
Please, Sign In to add comment