0% found this document useful (0 votes)
12 views

K214548 AI Lab 4.ipynb - Colaboratory

The document discusses solving the 8-puzzle problem using depth-first search (DFS) and breadth-first search (BFS). It defines an EightPuzzle class to represent puzzle states and includes methods for finding empty spaces and valid moves. DFS and BFS functions are provided to search for the goal state from a starting state.

Uploaded by

Uzair
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

K214548 AI Lab 4.ipynb - Colaboratory

The document discusses solving the 8-puzzle problem using depth-first search (DFS) and breadth-first search (BFS). It defines an EightPuzzle class to represent puzzle states and includes methods for finding empty spaces and valid moves. DFS and BFS functions are provided to search for the goal state from a starting state.

Uploaded by

Uzair
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

22/02/2024, 23:35 K214548 AI lab 4.

ipynb - Colaboratory

TASK 1

1 def neighbor(start):
2 n = len(dist_mat)
3 visited = set([start])
4 current = start
5 route = [current]
6 total_distance = 0
7
8 while len(visited) < n:
9 min_distance = float("inf")
10 next_city = None
11 for neighbor in range(n):
12 if neighbor not in visited and dist_mat[current][neighbor] < min_distance:
13 min_distance = dist_mat[current][neighbor]
14 next_city = neighbor
15 visited.add(next_city)
16 route.append(next_city)
17 current = next_city
18 total_distance += min_distance
19
20 route.append(start)
21 return route, total_distance
22
23
24 dist_mat = [
25 [0, 10, 15, 20],
26 [18, 0, 35, 25],
27 [15, 35, 0, 30],
28 [20, 25, 30, 0]
29 ]
30
31 start_city = 1
32
33 route, distance = neighbor(start_city)
34 print("\nCity Path:")
35 print(" -> ".join([f" {city}" for city in route]))
36 print(f"Total distance: {distance}")
37

City Path:
1 -> 0 -> 2 -> 3 -> 1
Total distance: 63

TASK 2 DFS on Graph

1 def dfs(g, s, visited=None):


2 if visited is None:
3 v = set()
4 visited.add(s)
5 print(s, end=' ')
6
7 for n in g[s]:
8 if n not in visited:
9 dfs(g, n, visited)
10
11 g = {
12 'A': ['B', 'C'],
13 'B': ['A', 'D', 'E'],
14 'C': ['A', 'F', 'G'],
15 'D': ['B'],
16 'E': ['B'],
17 'F': ['C'],
18 'G': ['C']
19 }
20
21 start_node = 'A'
22 print("DFS on Graph:")
23 dfs(g, start_node)
24

DFS on Graph:
A B D E C F G

Task 2 DFS on Tree

https://colab.research.google.com/drive/1lde9rcaPnPy0Q9b1tNWL0KoHqb6-GC3C?authuser=0#scrollTo=U6oCVOIEQ-_m&printMode=true 1/3
22/02/2024, 23:35 K214548 AI lab 4.ipynb - Colaboratory
1 class Node:
2 def __init__(self, v):
3 self.value = v
4 self.child = []
5
6 def dfs_tree(n):
7 print(n.value, end=' ')
8
9 for ch in n.child:
10 dfs_tree(ch)
11
12 r = Node('A')
13 r.child = [Node('B'), Node('C')]
14 r.child[0].child = [Node('D'), Node('E')]
15
16 print("\nDFS on Tree:")
17 dfs_tree(r)
18

DFS on Tree:
A B D E C

TASK 3

1 from collections import deque


2
3 class EightPuzzle:
4 def __init__(self, b, p=None):
5 self.board = b
6 self.parent = p
7
8 def __eq__(self, other):
9 return self.board == other.board
10
11 def __hash__(self):
12 return hash(str(self.board))
13
14 def __str__(self):
15 return '\n'.join([' '.join(map(str, row)) for row in self.board])
16
17 def empty_places(self):
18 for i in range(3):
19 for j in range(3):
20 if self.board[i][j] == 0:
21 return i, j
22
23 def empty_places_moves(self, direction):
24 curr_i, curr_j = self.empty_places()
25 i, j = curr_i, curr_j
26
27 if direction == 'up':
28 i -= 1
29 elif direction == 'down':
30 i += 1
31 elif direction == 'left':
32 j -= 1
33 elif direction == 'right':
34 j += 1
35
36 if i>= 0 and i< 3 and j>=0 and j < 3:
37 board = [row[:] for row in self.board]
38 board[curr_i][curr_j], board[i][j] = board[i][j], board[curr_i][curr_j]
39 return EightPuzzle(board, self)
40 else:
41 return None
42
43 def depth_first_search(Start_States, Final_states):
44 visited = set()
45 stack = [Start_States]
46
47 while stack:
48 current = stack.pop()
49
50 if current == Final_states:
51 return current
52
53 visited.add(current)
54
55 for direct in ['up', 'down', 'left', 'right']:
56 new_state = current.empty_places_moves(direct)
57 if new_state and new_state not in visited:
58 stack.append(new_state)
59
60
61 def breadth_first_search(Start_States, Final_states):
62 visited = set()
63 queue = deque([Start_States])
64
65 while queue:
66 current = queue.popleft()
67
68 if current == Final_states:
69 return current
70
71 visited.add(current)
72
73 for direct in ['up', 'down', 'left', 'right']:
74 next_state = current.empty_places_moves(direct)
https://colab.research.google.com/drive/1lde9rcaPnPy0Q9b1tNWL0KoHqb6-GC3C?authuser=0#scrollTo=U6oCVOIEQ-_m&printMode=true 2/3
22/02/2024, 23:35 K214548 AI lab 4.ipynb - Colaboratory
_ p y_p _ ( )
75 if next_state and next_state not in visited:
76 queue.append(next_state)
77
78 return None
79
80
81 Start_States = [[0, 8, 7],
82 [6, 5, 4],
83 [3, 2, 1]]
84 Final_states = [[0, 1, 2],
85 [3, 4, 5],
86 [6, 7, 8]]
87
88 Start_States = EightPuzzle(Start_States)
89 Final_states = EightPuzzle(Final_states)
90
91 print("Start States:")
92 print(Start_States)
93
94 print("\nDFS:")
95 dfs = depth_first_search(Start_States, Final_states)
96 print(dfs)
97
98 print("\nBFS:")
99 bfs = breadth_first_search(Start_States, Final_states)
100 print(bfs)
101

output Start States:


0 8 7
6 5 4
3 2 1

DFS:
0 1 2
3 4 5
6 7 8

BFS:
0 1 2
3 4 5
6 7 8

https://colab.research.google.com/drive/1lde9rcaPnPy0Q9b1tNWL0KoHqb6-GC3C?authuser=0#scrollTo=U6oCVOIEQ-_m&printMode=true 3/3

You might also like