0% found this document useful (0 votes)
46 views6 pages

Lab - Ai - DFS & BSF1

The document discusses implementing uninformed search algorithms like breadth-first search and depth-first search in Python. It provides pseudocode for BFS and DFS, shows examples of implementing them using an adjacency list representation of a graph, and outputs the traversals of sample graphs.

Uploaded by

Danial Khawaja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views6 pages

Lab - Ai - DFS & BSF1

The document discusses implementing uninformed search algorithms like breadth-first search and depth-first search in Python. It provides pseudocode for BFS and DFS, shows examples of implementing them using an adjacency list representation of a graph, and outputs the traversals of sample graphs.

Uploaded by

Danial Khawaja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

1.

Implementation of Uninformed search algorithms (BFS, DFS)

Aim:
To implement uninformed search algorithms such as BFS and DFS.

Algorithm:
Step 1: = Initialize an empty list called 'visited' to keep track of the nodes visited during the
traversal.
Step 2: = Initialize an empty queue called 'queue' to keep track of the nodes to be traversed
in the future.
Step 3: = Add the starting node to the 'visited' list and the 'queue'.
Step 4: = While the 'queue' is not empty, do the following:
a. Dequeue the first node from the 'queue' and store it in a variable called 'current'.
b. Print 'current'.
c. For each of the neighbours of 'current' that have not been visited yet, do the
following:
i. Mark the neighbour as visited and add it to the 'queue'.
Step 5: = When all the nodes reachable from the starting node have been visited, terminate
the algorithm.

Breadth First Search:


Initial state
Program:
graph = {
5
'5' : ['3','7'],
'3’: ['2', '4'],
'7' : ['8'], 3 7

'2' : [],
'4' : ['8'],
'8' : [] 2 4 8

}
visited = []
queue = []
def bfs(visited, graph, node):
visited.append(node)
queue.append(node)
while queue:
m = queue.pop(0)
print (m, end = " ")
for neighbour in graph[m]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
print("Following is the Breadth-First Search")
bfs(visited, graph, '5')
Output: Following is the Breadth-First Search
537248

Depth first Search:


Algorithm:
Step 1:= Initialize an empty set called 'visited' to keep track of the nodes visited during the
traversal.
Step 2:= Define a DFS function that takes the current node, the graph, and the 'visited' set
as input.
Step 3:= If the current node is not in the 'visited' set, do the following:
a. Print the current node.
b. Add the current node to the 'visited' set.
c. For each of the neighbours of the current node, call the DFS function recursively with
the neighbour as the current node.
Step 4:= When all the nodes reachable from the starting node have been visited, terminate
the algorithm.
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
visited = set()
def dfs(visited, graph, node):
if node not in visited:
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
print("Following is the Depth-First Search")
dfs(visited, graph, '5')
Output:
Following is the Depth-First Search
5
3
2
4
8
7
To implement BFS in python

PROGRAM:
from collections import deque
class Graph:
def __init__(self, adjac_list):
self.adjac_list = adjac_list
def bfs(self, start):
visited = set()
queue = deque([start])
while queue:
vertex = queue.popleft()
if vertex not in visited:
print(vertex, end=' ')
visited.add(vertex)
neighbors = self.adjac_list[vertex]
queue.extend(neighbors)
# Example usage:
adjac_list = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
graph = Graph(adjac_list)
start_node = 'A'
print("BFS Traversal:")
graph.bfs(start_node)
OUTPUT:
BFS Traversal:
ABCDEF
To implement the DFS using python

PROGRAM:
class Graph:
def __init__(self, adjac_list):
self.adjac_list = adjac_list
def dfs(self, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
print(start, end=' ')
for neighbor in self.adjac_list[start]:
if neighbor not in visited:
self.dfs(neighbor, visited)
# Example usage:
adjac_list = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
graph = Graph(adjac_list)
start_node = 'A'
print("DFS Traversal:")
graph.dfs(start_node)
OUTPUT:
DFS Traversal:
ABDEFC
Question 4.
A simple knowledgebase (KB) from the Kinship Domain Object relationships as a KB:
“Hasibis a parent ofRakib. Rakib is a parent ofSohel. Rakibis a parent ofRebeka. Rashidis a
parent ofHasib. If X is a parent of Y and Y is a parent of Z, then X is a grandparent of Z.”
List of tuples and sample procedure to manipulate the KB in Python:
tupleList1=[('parent', 'Hasib', 'Rakib'),('parent', 'Rakib', 'Sohel'),('parent', 'Rakib',
'Rebeka'),('parent', 'Rashid', 'Hasib')]
# Procedure to find the grandchildren of X
X=str(input("Grandparent:"))
print('Grandchildren:', end=' ')
i=0
while(i<=3):
if ((tupleList1[i][0] == 'parent')&( tupleList1[i][1] == X)):
for j in range(4):
if ((tupleList1[j][0] == 'parent') & ( tupleList1[i][2] == tupleList1[j][1])):
print(tupleList1[j][2], end=' ')

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy