0% found this document useful (0 votes)
17 views8 pages

54AIexp2

Uploaded by

Shrawani
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)
17 views8 pages

54AIexp2

Uploaded by

Shrawani
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/ 8

Experiment No.

2
Study and Implementation of Depth first search for problem
solving.
Date of Performance:
Date of Submission:
Vidyavardhini’s College of Engineering & Technology
Department of Computer Engineering

Aim: Study and Implementation of Depth first search for problem solving.
Objective: To study the uninformed searching techniques and its implementation for problem
solving.
Theory:
Artificial Intelligence is the study of building agents that act rationally. Most of the time,
these agents perform some kind of search algorithm in the background in order to achieve
their tasks.
● A search problem consists of:
● A State Space. Set of all possible states where you can be.
● A Start State. The state from where the search begins.
● A Goal Test. A function that looks at the current state returns whether or not it
is the goal state.
● The Solution to a search problem is a sequence of actions, called the plan that transforms
the start state to the goal state.
● This plan is achieved through search algorithms.

Depth First Search: DFS is an uninformed search method. It is also called blind search.
Uninformed search strategies use only the information available in the problem definition. A
search strategy is defined by picking the order of node expansion. Depth First Search (DFS)
searches deeper into the problem space. It is a recursive algorithm that uses the idea of
backtracking. It involves exhaustive searches of all the nodes by going ahead, if possible, else
by backtracking.

The basic idea is as follows:

Pick a starting node and push all its adjacent nodes into a stack.

Pop a node from stack to select the next node to visit and push all its adjacent nodes into a
stack.

Repeat this process until the stack is empty.

However, ensure that the nodes that are visited are marked. This will prevent you from
visiting the same node more than once. If you do not mark the nodes that are visited and you
visit the same node more than once, you may end up in an infinite loop.

Algorithm:

A standard DFS implementation puts each vertex of the graph into one of two categories:
CSL604: Artificial Intelligence Lab
Vidyavardhini’s College of Engineering & Technology
Department of Computer Engineering

1. Visited
2. Not Visited
The purpose of the algorithm is to mark each vertex as visited while avoiding cycles.
The DFS algorithm works as follows:
1.Start by putting any one of the graph's vertices on top of a stack.
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.
4.Keep repeating steps 2 and 3 until the stack is empty.

Pseudocode:

DFS-iterative (G, s): //Where G


is graph and s is source vertex
let S be stack
S.push( s ) //Inserting s in stack
mark s as visited.
while ( S is not empty):
//Pop a vertex from stack to visit next
v = S.top( )
S.pop( )
//Push all the neighbours of v in stack that are not
visited
for all neighbours w of v in Graph G:
if w is not visited :
S.push( w )
mark w as visited

DFS-recursive(G, s):
mark s as visited
for all neighbours w of s in Graph G:
if w is not visited:
DFS-recursive(G, w)

CSL604: Artificial Intelligence Lab


Vidyavardhini’s College of Engineering & Technology
Department of Computer Engineering

DFS Working: Example

Path: 1 🡪 2🡪 4🡪 5🡪 3

Searching Strategies are evaluated along the following dimensions:

1. Completeness: does it always find a solution if one exists?


2. Time complexity: number of nodes generated
3. Space complexity: maximum number of nodes in memory
4. Optimality: does it always find a least-cost solution?

Properties of depth-first search:

1. Complete:- No: fails in infinite-depth spaces, spaces with loops.


2. Time Complexity: O(bm)
3. Space Complexity: O(bm), i.e., linear space!
4. Optimal: No

Advantages of Depth-First Search:

1. Memory requirement is only linear with respect to the search graph.

CSL604: Artificial Intelligence Lab


Vidyavardhini’s College of Engineering & Technology
Department of Computer Engineering

2. The time complexity of a depth-first Search to depth d is O(b^d)


3. If depth-first search finds solution without exploring much in a path then the time and
space it takes will be very less.

Disadvantages of Depth-First Search:

1. There is a possibility that it may go down the left-most path forever. Even a finite
graph can generate an infinite tree.
2. Depth-First Search is not guaranteed to find the solution.
3. No guarantee to find an optimum solution, if more than one solution exists.

Applications

How to find connected components using DFS?

A graph is said to be disconnected if it is not connected, i.e. if two nodes exist in the graph
such that there is no edge in between those nodes. In an undirected graph, a connected
component is a set of vertices in a graph that are linked to each other by paths.

Consider the example given in the diagram. Graph G is a disconnected graph and has the
following 3 connected components.

● First connected component is 1 🡪 2 🡪 3 as they are linked to each other


● Second connected component 4 🡪 5
● Third connected component is vertex 6

Code:
DFA:

Input:

def dfs(tree, current, visited=None, goal=None):

if visited is None:

visited = set()

visited.add(current)

print(current, end=' ')


CSL604: Artificial Intelligence Lab
Vidyavardhini’s College of Engineering & Technology
Department of Computer Engineering

if goal is not None and current == goal:

print("\nGoal vertex reached!")

return

for child in tree.get(current, []):

if child not in visited:

dfs(tree, child, visited, goal)

# Take input for the tree

tree = {}

num_nodes = int(input("Enter the number of nodes in the tree: "))

for _ in range(num_nodes - 1):

edge = input("Enter edge (format: parent child): ").split()

parent, child = edge

if parent not in tree:

tree[parent] = []

tree[parent].append(child)

# Take input for the starting node

start_node = input("Enter the starting node: ")

# Take input for the goal node

goal_node = input("Enter the goal node (or leave blank for regular DFS): ")

CSL604: Artificial Intelligence Lab


Vidyavardhini’s College of Engineering & Technology
Department of Computer Engineering

# Perform DFS on the tree

print("Depth-First Search:")

dfs(tree, start_node, goal=goal_node if goal_node else None)

Output:

Enter the number of nodes in the tree: 7

Enter edge (format: parent child): 9 7

Enter edge (format: parent child): 9 3

Enter edge (format: parent child): 7 5

Enter edge (format: parent child): 7 1

Enter edge (format: parent child): 3 2

Enter edge (format: parent child): 3 4

Enter the starting node: 9

Enter the goal node (or leave blank for regular DFS): 1

Depth-First Search:

9751

Goal vertex reached!

Conclusion:
In conclusion, the Depth-First Search (DFS) algorithm provides a fundamental graph

traversal technique, exploring deeply using a stack (or recursion). DFS is well-suited for tasks

like topological sorting. It exhibits a time complexity of O(V + E), where V is the number of

vertices and E is the number of edges. Performance depends on the choice of data structure

CSL604: Artificial Intelligence Lab


Vidyavardhini’s College of Engineering & Technology
Department of Computer Engineering

and graph structure. Rigorous testing on diverse graphs and validation against established

problems ensures correctness and efficiency.

CSL604: Artificial Intelligence Lab

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