Professional Documents
Culture Documents
Experiment No. 2: Aim: Theory
Experiment No. 2: Aim: Theory
B4-764
Experiment No. 2
Theory:
DFS is an uninformed search technique. In DFS search tree is expanded depth wise; i.e. the deepest
node in the current branch of the search tree as expanded. As the leaf node is reached, the search
backtracks to previous node. It starts from the root node and goes deeper and deeper until a goal
node is found or until it hits a node having no children. Then the search backtracks, returning to the
most recent node it hasn’t finished exploring.
2. Take the top item of the stack and add it to the visited list.
3. Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited list to the top
of the stack.
Example-
As C does not have any unvisited adjacent node so we keep popping the stack until we find a node
that has an unvisited adjacent node. In this case, there's none and we keep popping until the stack is
empty.
Time complexity: A DFS, may generate all the O (bm) nodes in the search tree, where m is the
maximum depth of any node; this can be much greater than the size of the state space.
Space complexity: For a search tree with branching factor b and maximum depth m, DFS requires
storage of only O (bm) nodes, as at a time only the branch, which is getting explored, will reside in
memory.
Code:
# Using a Python dictionary to act as an adjacency list graph
={
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}
visited = set() # Set to keep track of visited nodes.
def dfs(visited, graph, node): if node not in
visited: print (node) visited.add(node)
for neighbour in graph[node]: dfs(visited,
graph, neighbour)
# Driver Code
dfs(visited, graph, 'A')
Output: