11import copy
22import heapq
33
4+
45class Puzzle :
5-
66 def __init__ (self , initial_state ):
77 self .goal_state = [[1 , 2 , 3 ], [4 , 5 , 6 ], [7 , 8 , 0 ]]
88 self .initial_state = initial_state
99 self .open_list = []
1010 self .closed_list = []
11-
11+
1212 def get_heuristic (self , state ):
1313 heuristic = 0
1414 for i in range (3 ):
@@ -17,39 +17,47 @@ def get_heuristic(self, state):
1717 x_goal , y_goal = divmod (state [i ][j ] - 1 , 3 )
1818 heuristic += abs (i - x_goal ) + abs (j - y_goal )
1919 return heuristic
20-
20+
2121 def get_blank_position (self , state ):
2222 for i in range (3 ):
2323 for j in range (3 ):
2424 if state [i ][j ] == 0 :
2525 return (i , j )
26-
26+
2727 def get_successors (self , state ):
2828 successors = []
2929 i_blank , j_blank = self .get_blank_position (state )
3030 for x , y in [(0 , 1 ), (1 , 0 ), (0 , - 1 ), (- 1 , 0 )]:
3131 if 0 <= i_blank + x < 3 and 0 <= j_blank + y < 3 :
3232 new_state = copy .deepcopy (state )
33- new_state [i_blank ][j_blank ], new_state [i_blank + x ][j_blank + y ] = new_state [i_blank + x ][j_blank + y ], new_state [i_blank ][j_blank ]
33+ new_state [i_blank ][j_blank ], new_state [i_blank + x ][j_blank + y ] = (
34+ new_state [i_blank + x ][j_blank + y ],
35+ new_state [i_blank ][j_blank ],
36+ )
3437 successors .append (new_state )
3538 return successors
36-
39+
3740 def solve (self ):
38- start_node = (self .get_heuristic (self .initial_state ), self .initial_state , 0 , None )
41+ start_node = (
42+ self .get_heuristic (self .initial_state ),
43+ self .initial_state ,
44+ 0 ,
45+ None ,
46+ )
3947 heapq .heappush (self .open_list , start_node )
40-
48+
4149 while self .open_list :
4250 current_node = heapq .heappop (self .open_list )
4351 current_cost = current_node [2 ]
4452 current_state = current_node [1 ]
45-
53+
4654 if current_state == self .goal_state :
4755 path = []
4856 while current_node :
4957 path .append (current_node [1 ])
5058 current_node = current_node [3 ]
5159 return reversed (path )
52-
60+
5361 self .closed_list .append (current_state )
5462 successors = self .get_successors (current_state )
5563 for successor in successors :
@@ -59,11 +67,12 @@ def solve(self):
5967 f_cost = g_cost + h_cost
6068 new_node = (f_cost , successor , g_cost , current_node )
6169 heapq .heappush (self .open_list , new_node )
62-
70+
6371 return None
6472
73+
6574# Run the Solver
66- initial_state = [[1 ,2 , 3 ], [4 ,5 , 6 ], [0 ,7 , 8 ]]
75+ initial_state = [[1 , 2 , 3 ], [4 , 5 , 6 ], [0 , 7 , 8 ]]
6776solver = Puzzle (initial_state )
6877solution = solver .solve ()
6978
@@ -74,4 +83,4 @@ def solve(self):
7483 print (row )
7584 print ()
7685else :
77- print ("No solution found." )
86+ print ("No solution found." )
0 commit comments