-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS.py
More file actions
74 lines (63 loc) · 1.35 KB
/
Copy pathBFS.py
File metadata and controls
74 lines (63 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#code for Breadth First Search
def BFS(graph, initial, goal):
queue = []
visited = set()
parent = {}
queue.append(initial)
visited.add(initial)
while queue:
state = queue.pop(0)
if state == goal:
path = [goal]
while path[-1] != initial:
path.append(parent[path[-1]])
path.reverse()
return path, visited
for neighbour in graph[state]:
if neighbour not in visited:
queue.append(neighbour)
visited.add(neighbour)
parent[neighbour] = state
return None, visited
with open("i1.txt") as f:
num_states = int(f.readline())
graph = {}
for i in range(1, num_states + 1):
neighbours = list(map(int, f.readline().split()))
graph[i] = neighbours
initial = int(f.readline())
goal = int(f.readline())
path, visited = BFS(graph, initial, goal)
if path:
print("Traversed States:", visited)
print("Path from Initial State to Goal State:", path)
else:
if goal not in graph.keys():
print("Goal state not present in the state space.")
else:
print("Goal state not approachable from the initial state.")
'''
i1.txt
8
1 2 4
1 2 5
3 4 7
3 4
5 6
5 6 8
7 8
7 8
1
7
--------------------------------------
i2.txt
7
2 3
4 5
6 7
5
7
4
1
6
'''