Menu

Artificial Intelligence Using Python [ Lab Programs ]


Write a Program to implement Depth First Search (DFS) 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']
}
# Set used to store visited nodes.
visitedNodes = list()
# function
def dfs(visitedNodes, graph, node):
	if node not in visitedNodes:
		print (node,end=" ")
		visitedNodes.append(node)
		for neighbour in graph[node]:
			dfs(visitedNodes, graph, neighbour)
# Driver Code
snode = input("Enter Starting Node(A, B, C, D, or E) :").upper()
# calling bfs function
print("RESULT :")
print("-"*20)
dfs(visitedNodes, graph, snode)

OUTPUT :

Sample Output 1: 

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

------------------------------------------------------------------
Sample Output 2: 

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

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