Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2020
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. #!/bin/python3
  2.  
  3. import math
  4. import os
  5. import random
  6. import re
  7. import sys
  8.  
  9.  
  10.  
  11. #
  12. # Complete the 'movesToSolve' function below.
  13. #
  14. # The function is expected to return an INTEGER.
  15. # The function accepts 2D_INTEGER_ARRAY puzzle as parameter.
  16. #
  17. from collections import deque
  18. import copy
  19.  
  20. def zeroLocation(puzzle): # Helper function to return X,Y coordinates of 0 square
  21. for i in range(len(puzzle)):
  22. for j in range(len(puzzle[0])):
  23. if puzzle[i][j] == 0:
  24. return (i,j)
  25.  
  26. def neighbors(puzzle):
  27. X, Y = len(puzzle), len(puzzle[0])
  28. neighbors = []
  29. x_zero, y_zero = zeroLocation(puzzle)
  30. for x,y in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
  31. x_new = x_zero + x
  32. y_new = y_zero + y
  33. if 0 <= x_new < X and 0 <= y_new < Y:
  34. new_board = copy.deepcopy(puzzle)
  35. new_board[x_zero][y_zero], new_board[x_new][y_new] = new_board[x_new][y_new], new_board[x_zero][y_zero]
  36. neighbors.append(new_board)
  37. return neighbors
  38.  
  39.  
  40. def movesToSolve(puzzle):
  41. # Write your code here
  42. nRows = len(puzzle)
  43. mRows = len(puzzle[0])
  44. solved = [[0 for x in range(nRows)] for y in range(mRows)]
  45. counter = 0 # Generate Solved Board to check for Goal
  46. for i in range(nRows):
  47. for j in range(mRows):
  48. solved[i][j] = counter
  49. counter += 1
  50. if puzzle == solved:
  51. return 0
  52.  
  53. queue = deque()
  54. queue.append((puzzle,[puzzle]))
  55. seen = []
  56.  
  57. while queue:
  58. current, path = queue.popleft()
  59. neighbs = neighbors(current)
  60. for p in path:
  61. if p in neighbs: neighbs.remove(p)
  62. for neighbor in neighbs:
  63. if neighbor not in seen:
  64. if neighbor == solved:
  65. return(len(path)) # Number of Moves
  66. exit()
  67. else:
  68. queue.append((neighbor, path+[neighbor]))
  69. for x in neighbs: seen.append(x)
  70. return -1
  71.  
  72.  
  73.  
  74.  
  75. if __name__ == '__main__':
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement