Exp 1 PDF
Exp 1 PDF
NO:1
Write a Program to implement 8-Puzzle problem using Python.
Aim: Write a program to implement 8-Puzzle problem usingPython.
Algorithm:
Program: 1
class Solution:
dict = {} flatten
= []
+= board[i] flatten
= tuple(flatten)
dict[flatten] = 0
return 0
return
dict):
cnt]if len(current_nodes) == 0:
return -1
self.find_next(node)for move in
next_moves:
dict[move] = cnt + 1
if move == (0, 1, 2, 3, 4, 5, 6, 7, 8):
return cnt + 1
1: [0, 2, 4],
2: [1, 5],
3: [0, 4, 6],
4: [1, 3, 5, 7],
5: [2, 4, 8],
6: [3, 7],
7: [4, 6, 8],
8: [5, 7],
results = []
pos_0 =
node.index(0) for
move in
moves[pos_0]:
new_node
= list(node)
new_node[move] results.append(tuple(new_node))
return results
ob = Solution( )matrix = [
[3, 1, 2],
[4, 7, 5],
[6, 8, 0]
]
print("NO OF MOVES==",ob.solve(matrix))
OUTPUT:
NO OF MOVES== 4
Program : 2
1. import copy
2. from heapq import heappush, heappop
3. n=3
4. rows = [ 1, 0, -1, 0 ]
5. cols = [ 0, -1, 0, 1 ]
6.
7. # creating a class for the Priority Queue
8. class priorityQueue:
9. def __init__(self):
10. self.heap = []
11.
12. # Inserting a new key 'key'
13. def push(self, key):
14. heappush(self.heap, key)
15.
16. # funct to remove the element that is minimum,
17. # from the Priority Queue
18. def pop(self):
19. return heappop(self.heap)
20.
21. # funct to check if the Queue is empty or not
22. def empty(self):
23. if not self.heap:
24. return True
25. else:
26. return False
27.
28. # structure of the node
29. class nodes:
30.
31. def __init__(self, parent, mats, empty_tile_posi,
32. costs, levels):
33.
34. # This will store the parent node to the
35. # current node And helps in tracing the
36. # path when the solution is visible
37. self.parent = parent
38.
39. # Useful for Storing the matrix
40. self.mats = mats
41.
42. # useful for Storing the position where the
43. # empty space tile is already existing in the matrix
44. self.empty_tile_posi = empty_tile_posi
45.
46. # Store no. of misplaced tiles
47. self.costs = costs
48.
49. # Store no. of moves so far
50. self.levels = levels
51.
52. # This func is used in order to form the
53. # priority queue based on
54. # the costs var of objects
55. def __lt__(self, nxt):
56. return self.costs < nxt.costs
57.
58. # method to calc. the no. of
59. # misplaced tiles, that is the no. of non-blank
60. # tiles not in their final posi
61. def calculateCosts(mats, final) -> int:
62.
63. count = 0
64. for i in range(n):
65. for j in range(n):
66. if ((mats[i][j]) and
67. (mats[i][j] != final[i][j])):
68. count += 1
69.
70. return count
71.
72. def newNodes(mats, empty_tile_posi, new_empty_tile_posi,
73. levels, parent, final) -> nodes:
74.
75. # Copying data from the parent matrixes to the present matrixes
76. new_mats = copy.deepcopy(mats)
77.
78. # Moving the tile by 1 position
79. x1 = empty_tile_posi[0]
80. y1 = empty_tile_posi[1]
81. x2 = new_empty_tile_posi[0]
82. y2 = new_empty_tile_posi[1]
83. new_mats[x1][y1], new_mats[x2][y2] = new_mats[x2][y2], new_mats[x1][y1]
84.
85. # Setting the no. of misplaced tiles
86. costs = calculateCosts(new_mats, final)
87.
88. new_nodes = nodes(parent, new_mats, new_empty_tile_posi,
89. costs, levels)
90. return new_nodes
91.
92. # func to print the N by N matrix
93. def printMatsrix(mats):
94.
95. for i in range(n):
96. for j in range(n):
97. print("%d " % (mats[i][j]), end = " ")
98.
99. print()
100.
101. # func to know if (x, y) is a valid or invalid
102. # matrix coordinates
103. def isSafe(x, y):
104.
105. return x >= 0 and x < n and y >= 0 and y < n
106.
107. # Printing the path from the root node to the final node
108. def printPath(root):
109.
110. if root == None:
111. return
112.
113. printPath(root.parent)
114. printMatsrix(root.mats)
115. print()
116.
117. # method for solving N*N - 1 puzzle algo
118. # by utilizing the Branch and Bound technique. empty_tile_posi is
119. # the blank tile position initially.
120. def solve(initial, empty_tile_posi, final):
121.
122. # Creating a priority queue for storing the live
123. # nodes of the search tree
124. pq = priorityQueue()
125.
126. # Creating the root node
127. costs = calculateCosts(initial, final)
128. root = nodes(None, initial,
129. empty_tile_posi, costs, 0)
130.
131. # Adding root to the list of live nodes
132. pq.push(root)
133.
134. # Discovering a live node with min. costs,
135. # and adding its children to the list of live
136. # nodes and finally deleting it from
137. # the list.
138. while not pq.empty():
139.
140. # Finding a live node with min. estimatsed
141. # costs and deleting it form the list of the
142. # live nodes
143. minimum = pq.pop()
144.
145. # If the min. is ans node
146. if minimum.costs == 0:
147.
148. # Printing the path from the root to
149. # destination;
150. printPath(minimum)
151. return
152.
153. # Generating all feasible children
154. for i in range(n):
155. new_tile_posi = [
156. minimum.empty_tile_posi[0] + rows[i],
157. minimum.empty_tile_posi[1] + cols[i], ]
158.
159. if isSafe(new_tile_posi[0], new_tile_posi[1]):
160.
161. # Creating a child node
162. child = newNodes(minimum.mats,
163. minimum.empty_tile_posi,
164. new_tile_posi,
165. minimum.levels + 1,
166. minimum, final,)
167.
168. # Adding the child to the list of live nodes
169. pq.push(child)
170.
171. # Main Code
172.
173. # Initial configuration
174. # Value 0 is taken here as an empty space
175. initial = [ [ 1, 2, 3 ],
176. [ 5, 6, 0 ],
177. [ 7, 8, 4 ] ]
178.
179. # Final configuration that can be solved
180. # Value 0 is taken as an empty space
181. final = [ [ 1, 2, 3 ],
182. [ 5, 8, 6 ],
183. [ 0, 7, 4 ] ]
184.
185. # Blank tile coordinates in the
186. # initial configuration
187. empty_tile_posi = [ 1, 2 ]
188.
189. # Method call for solving the puzzle
190. solve(initial, empty_tile_posi, final)
Output :
123
560
784
123
506
784
123
586
704
Result: Thus the program to implement 8-Puzzle problem is executed and the output is
obtained.