Menu

Artificial Intelligence Using Python [ Lab Programs ]


Write a Program to implement Breadth First Search (BFS) using Python.

Input Graph

SOURCE CODE :

 # Input Graph
graph = {
'A' : ['B','C'],
'B' : ['A','C','D'],
'C' : ['A','B','E'],
'D' : ['B','E'],
'E' : ['C','D']
}
# To store visited nodes.
visitedNodes = []
# To store nodes in queue
queueNodes = [] 
# function
def bfs(visitedNodes, graph, snode):
	visitedNodes.append(snode)
	queueNodes.append(snode)
	print()
	print("RESULT :")
	while queueNodes:
		s = queueNodes.pop(0)
		print (s, end = " ")
		for neighbour in graph[s]:
			if neighbour not in visitedNodes:
				visitedNodes.append(neighbour)
				queueNodes.append(neighbour)
		
# Main Code
snode = input("Enter Starting Node(A, B, C, D, or E) :").upper()
# calling bfs function
bfs(visitedNodes, graph, snode)

OUTPUT :

Sample Output 1: 
-------------------
Enter Starting Node(A, B, C, D, or E) :A

RESULT :
A B C D E
------------------------------------------------------------------
Sample Output 2: 
-------------------
Enter Starting Node(A, B, C, D, or E) :B

RESULT :
B A C D E

Related Content :

Artificial Intelligence Using Python

   Write a Program to Implement the following using Python

1) Breadth First Search View Solution

2) Depth First Search View Solution

3) Tic-Tac-Toe game View Solution

4) 8-Puzzle problem View Solution

5) Water-Jug problem View Solution

6) Travelling Salesman Problem View Solution

7) Tower of Hanoi View Solution

8) Monkey Banana Problem View Solution

9) Alpha-Beta Pruning View Solution

10) 8-Queens Problem View Solution