Skip to content

Commit 2f1c5ed

Browse files
authored
Create NPuzzle_wo_class.py
1 parent 1b6e538 commit 2f1c5ed

File tree

1 file changed

+128
-0
lines changed

1 file changed

+128
-0
lines changed
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
#Author : Ajinkya Sonawane
2+
3+
def accept():
4+
temp = []
5+
for i in range(0,3):
6+
inp = input().split(' ')
7+
temp.append(inp)
8+
9+
return temp
10+
11+
def f(start,goal,level):
12+
return h(start,goal) + (level+1)
13+
14+
def h(start,goal):
15+
count = 0
16+
for i in range(0,len(goal)):
17+
for j in range(0,len(goal)):
18+
if goal[i][j] != start[i][j] and goal[i][j] != '_' :
19+
count += 1
20+
return count
21+
22+
def copy(puz):
23+
temp = []
24+
for i in range(0,len(puz)):
25+
x = []
26+
for j in range(0,len(puz)):
27+
x.append(puz[i][j])
28+
temp.append(x)
29+
30+
return temp
31+
32+
33+
def shuffle(puz,x1,y1,x2,y2):
34+
puz = copy(puz)
35+
if x2 >= len(puz) or x2 < 0 or y2 >= len(puz) or y2 < 0:
36+
return None
37+
38+
temp = puz[x1][y1]
39+
puz[x1][y1] = puz[x2][y2]
40+
puz[x2][y2] = temp
41+
42+
return puz
43+
44+
45+
def find(puz,char):
46+
for i in range(0,len(puz)):
47+
for j in range(0,len(puz)):
48+
if puz[i][j] == char:
49+
return i,j
50+
51+
def generate_child(puz):
52+
x,y = find(puz,'_')
53+
positions = [[x+1,y],
54+
[x-1,y],
55+
[x,y+1],
56+
[x,y-1]]
57+
children = []
58+
59+
for pos in positions:
60+
child = shuffle(puz,x,y,pos[0],pos[1])
61+
if child != None:
62+
children.append(child)
63+
64+
return children
65+
66+
67+
def present(ol,cl,child):
68+
for i in ol:
69+
if h(i['puz'],child) == 0:
70+
return True
71+
for i in cl:
72+
if h(i['puz'],child) == 0:
73+
return True
74+
75+
return False
76+
77+
print('Enter the start configuration')
78+
start = accept()
79+
print('Enter the goal configuration')
80+
goal = accept()
81+
82+
open_list = []
83+
close_list = []
84+
85+
"""
86+
f(n) = h(n) + g(n)
87+
"""
88+
89+
open_list.append(
90+
{
91+
'id':0,
92+
'puz':start,
93+
'f':f(start,goal,-1),
94+
'g':0,
95+
'prev':None
96+
})
97+
id = 0
98+
while True:
99+
cur_node = open_list[0]
100+
if h(cur_node['puz'],goal) == 0:
101+
break
102+
103+
children = generate_child(cur_node['puz'])
104+
105+
for child in children:
106+
if not present(open_list,close_list,child):
107+
id += 1
108+
open_list.append({
109+
'id':id,
110+
'puz':child,
111+
'f':f(child,goal,cur_node['g']),
112+
'g':cur_node['g']+1,
113+
'prev':cur_node['id']
114+
})
115+
116+
close_list.append(cur_node)
117+
del open_list[0]
118+
119+
open_list.sort(key=lambda x:x['f'],reverse=False)
120+
121+
stack = []
122+
stack.append(open_list[0])
123+
close_list.reverse()
124+
cur_id = open_list[0]['prev']
125+
for i in close_list:
126+
if i['id'] == cur_id:
127+
stack.append(i)
128+
cur_id = i['prev']

0 commit comments

Comments
 (0)