Experiment-2: AIM: WAP To Implement Depth First Search and Breadth Search Algorithms. Theory
Experiment-2: AIM: WAP To Implement Depth First Search and Breadth Search Algorithms. Theory
AIM: WAP to implement depth first search and breadth search algorithms.
Theory:
The Depth-First Search is a recursive algorithm that uses the concept of backtracking. It
involves thorough searches of all the nodes by going ahead if potential, else by backtracking.
Here, the word backtrack means once you are moving forward and there are not any more nodes
along the present path, you progress backward on an equivalent path to seek out nodes to
traverse. All the nodes are progressing to be visited on the current path until all the unvisited
nodes are traversed after which subsequent paths are going to be selected. The DSF algorithm
follows as:
1. We will start by putting any one of the graph's vertex on top of the stack.
2. After that take the top item of the stack and add it to the visited list of the vertex.
3. Next, create a list of that adjacent node of the vertex. Add the ones which aren't in the
visited list of vertexes to the top of the stack.
4. Lastly, keep repeating steps 2 and 3 until the stack is empty.
Breadth-First Search (BFS) is an algorithm used for traversing graphs or trees. Traversing
means visiting each node of the graph. Breadth-First Search is a recursive algorithm to search all
the vertices of a graph or a tree. BFS in python can be implemented by using data structures like
a dictionary and lists. Breadth-First Search in tree and graph is almost the same. The only
difference is that the graph may contain cycles, so we may traverse to the same node again.The
steps of the algorithm work as follow:
1. Start by putting any one of the graph’s vertices at the back of the queue.
2. Now take the front item of the queue and add it to the visited list.
3. Create a list of that vertex's adjacent nodes. Add those which are not within the visited
list to the rear of the queue.
4. Keep continuing steps two and three till the queue is empty.
Coding:
Depth first search:
graph = {
'5' : ['3','7'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
visited = set()
print (node)
visited.add(node)
OUTPUT:
'5' : ['3','7'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
visited = []
queue = []
visited.append(node)
queue.append(node)
while queue:
m = queue.pop(0)
visited.append(neighbour)
queue.append(neighbour)
OUTPUT:
Result:
The program is successfully written and compiled in python.