Program To Find Number of Steps To Solve 8-Puzzle in Python
Program To Find Number of Steps To Solve 8-Puzzle in Python
Suppose we have a 3x3 board of where all numbers are in range 0 to 8 and no repeating numbers
are there. Now, we can swap the 0 with one of its 4 neighbors, and we are trying to solve it to get all
arranged sequence, we have to find minimum number of steps required to reach the goal.
3 1 2
4 7 5
6 8 0
https://www.tutorialspoint.com/program-to-find-number-of-steps-to-solve-8-puzzle-in-python 1/4
1/5/2021 Program to find number of steps to solve 8-puzzle in python
next_moves := find_next(node)
for each move in next_moves, do
if move is not present in dict, then
dict[move] := cnt + 1
if move is same as (0, 1, 2, 3, 4, 5, 6, 7, 8) , then
return cnt + 1
cnt := cnt + 1
From the main method do the following:
dict := a new map, flatten := a new list
for i in range 0 to row count of board, do
flatten := flatten + board[i]
flatten := a copy of flatten
dict[flatten] := 0
if flatten is same as (0, 1, 2, 3, 4, 5, 6, 7, 8) , then
return 0
return get_paths(dict)
Example
Live Demo
class Solution:
def solve(self, board):
dict = {}
flatten = []
for i in range(len(board)):
flatten += board[i]
flatten = tuple(flatten)
dict[flatten] = 0
return self.get_paths(dict)
return -1
results = []
pos_0 = node.index(0)
for move in moves[pos_0]:
new_node = list(node)
new_node[move], new_node[pos_0] = new_node[pos_0], new_node[move]
results.append(tuple(new_node))
return results
ob = Solution()
matrix = [
[3, 1, 2],
[4, 7, 5],
[6, 8, 0]
]
print(ob.solve(matrix))
Input
matrix = [
[3, 1, 2],
[4, 7, 5],
[6, 8, 0] ]
https://www.tutorialspoint.com/program-to-find-number-of-steps-to-solve-8-puzzle-in-python 3/4
1/5/2021 Program to find number of steps to solve 8-puzzle in python
Output
4
https://www.tutorialspoint.com/program-to-find-number-of-steps-to-solve-8-puzzle-in-python 4/4