K214548 AI Lab 4.ipynb - Colaboratory
K214548 AI Lab 4.ipynb - Colaboratory
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
DFS on Graph:
A B D E C F G
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
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