0% found this document useful (0 votes)
89 views20 pages

BFS and DFS

The document discusses search algorithms used in artificial intelligence. It describes two categories of search algorithms - uninformed and informed. Uninformed algorithms like breadth-first search and depth-first search do not use heuristics to guide the search, while informed algorithms like A* use heuristics. It provides details on the breadth-first search and depth-first search algorithms, including their implementations and properties.

Uploaded by

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

BFS and DFS

The document discusses search algorithms used in artificial intelligence. It describes two categories of search algorithms - uninformed and informed. Uninformed algorithms like breadth-first search and depth-first search do not use heuristics to guide the search, while informed algorithms like A* use heuristics. It provides details on the breadth-first search and depth-first search algorithms, including their implementations and properties.

Uploaded by

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

Searching Algortihms in AI

• In artificial intelligence, search algorithms are


broadly classified into two categories:
• Informed search algorithms.
• Uninformed search algorithms.
Uninformed Search Algorithms
• Uninformed search algorithms are those in which
the algorithm does not have any information about
the problem or the goal. They are also known as
blind search algorithms. These algorithms explore
the search space in a systematic way and do not use
any heuristics or domain-specific knowledge to
guide their search. Examples of uninformed search
algorithms include Breadth-First Search (BFS),
Depth-First Search (DFS), and Uniform-Cost Search
(UCS).
Informed Search Algorithms
• Informed search algorithms are those that use
domain-specific knowledge to guide the search
towards the goal. They are also known as heuristic
search algorithms. These algorithms use heuristics
to estimate the distance or cost to the goal, and
they explore the search space in a way that is
more likely to lead to the goal state. Examples of
informed search algorithms include Best-First
Search (BFS), A* Search, and Greedy Search.
• Both informed and uninformed search algorithms
have their advantages and disadvantages.
Uninformed search algorithms are easy to implement
and are guaranteed to find a solution if one exists, but
they can be very slow and can waste a lot of time
exploring irrelevant parts of the search space.
Informed search algorithms are often faster and more
efficient, but they require domain-specific knowledge,
which may not always be available, and they are not
guaranteed to find a solution even if one exists.
• Breadth-First Search (BFS) is a popular graph
traversal algorithm that is used to explore all the
vertices in a graph in a systematic manner. The
algorithm starts at the root node and explores all
the neighbors of the root node first, then moves to
the neighbors of the neighbors, and so on, until all
the nodes in the graph have been explored. BFS is a
commonly used algorithm in many applications,
including social networks, web crawling, and
network analysis
• The basic idea behind BFS is to visit all nodes
or vertices of a graph or tree in breadth-first
order, starting from a specified root or starting
node. It maintains a "frontier" of nodes that
have been visited but whose neighbors have
not yet been visited. Starting from the root
node, BFS visits all nodes at the current depth
before moving onto the next level.
• One important aspect of BFS is that it requires
the use of a queue to keep track of the order in
which nodes are visited. The algorithm starts by
adding the root node to the queue, and then
repeatedly dequeues the next node in the
queue and adds its neighbors to the queue. This
ensures that nodes at a shallower depth are
visited before nodes at a deeper depth, which is
key to ensuring that the shortest path is found.
• In the case of an unweighted graph, BFS is
guaranteed to find the shortest path between
two nodes, since it visits all nodes at each
depth before moving onto the next depth.
However, in the case of a weighted graph, BFS
is not guaranteed to find the shortest path,
since it does not take into account the weight
of the edges.
• In Python, BFS can be implemented using a
queue data structure, such as the deque class
from the collections module. The algorithm
starts by adding the root node to the queue,
and then repeatedly dequeues the next node
in the queue and adds its neighbors to the
queue. To prevent visiting the same node
multiple times, we keep track of visited nodes
in a set.
Code Implementation
• from collections import deque

• def bfs(graph, start):


• visited = set()
• queue = deque([start])
• while queue:
• vertex = queue.popleft()
• if vertex not in visited:
• visited.add(vertex)
• print(vertex)
• queue.extend(graph[vertex] - visited)

• # Example usage:
• graph = {
• 'A': {'B', 'C'},
• 'B': {'A', 'D', 'E'},
• 'C': {'A', 'F', 'G'},
• 'D': {'B'},
• 'E': {'B', 'G'},
• 'F': {'C'},
• 'G': {'C', 'E'}
• }

• bfs(graph, 'A')
If the goal is provided
• from collections import deque

• def bfs(graph, start, goal):


• visited = set()
• queue = deque([start])
• while queue:
• vertex = queue.popleft()
• if vertex == goal:
• print("Goal found!")
• return True
• if vertex not in visited:
• visited.add(vertex)
• print(vertex)
• queue.extend(graph[vertex] - visited)
• print("Goal not found.")
• return False

• # Example usage:
• graph = {
• 'A': {'B', 'C'},
• 'B': {'A', 'D', 'E'},
• 'C': {'A', 'F', 'G'},
• 'D': {'B'},
• 'E': {'B', 'G'},
• 'F': {'C'},
• 'G': {'C', 'E'}
• }

• bfs(graph, 'A', 'G')


Code Explanation
• We start by importing the deque class from the collections module. We will use this class to
implement the queue data structure, which is used to keep track of the nodes that we need to
explore.
• The bfs function takes two arguments: the graph as a dictionary, and the starting vertex for the
traversal.
• We initialize two data structures: the visited set, which keeps track of the nodes that we have already
explored, and the queue deque, which is initially populated with the starting vertex.
• We enter a while loop that continues until the queue is empty. This loop is the heart of the BFS
algorithm, where we explore the vertices in the graph.
• We retrieve the first vertex from the left side of the queue using the popleft method, which removes
the vertex from the queue. We use a deque instead of a regular list as the queue data structure
because it allows us to efficiently add and remove elements from both ends of the queue.
• If the vertex has not already been visited, we add it to the visited set, print its value to the console,
and add its neighbors to the queue using the extend method. The extend method adds all the
elements of a set to the end of the deque.
• We repeat this process until we have explored all the vertices in the graph.
• Finally, we return the visited set, which contains all the vertices that we explored during the BFS
traversal.
Take Aways from BFS
• Key Points:
• Uninformed Search Technique
• Queue(FIFO approach)
• Shortest Node
• Optimal
• Time Complexity: O(b^d) where b stands for
branching factor and d stands depth
Depth First Search
• Depth-First Search (DFS) is a traversal
algorithm that is used to explore all the
vertices of a graph or a tree. The DFS
algorithm starts at the root node of the tree or
graph and visits all the vertices in a depth-first
manner. In other words, it starts from a vertex,
goes as deep as possible along each branch
before backtracking.
• DFS is a searching algorithm that explores a tree or graph by going as
far as possible down a particular path before backtracking.
• DFS is a blind search technique, meaning that it does not use any
knowledge about the problem domain to guide the search. It simply
explores the search space until it finds a solution or exhausts all
possibilities.
• DFS can be implemented using either a recursive or iterative approach.
The recursive approach is more elegant, but it can run into problems
with very deep search trees due to Python's default recursion limit.
The iterative approach avoids this problem by using a stack to keep
track of the nodes to be explored.
• DFS can be used to solve a variety of problems in AI, including
pathfinding, game playing, and planning.
• DFS has some drawbacks compared to other
search algorithms, such as Breadth-First
Search (BFS) and A* Search. One major
drawback is that it can get stuck in infinite
loops if it encounters cycles in the search
space. It also does not guarantee finding the
optimal solution.
Implementation
• graph = {'A': set(['B', 'C']),
• 'B': set(['A', 'D', 'E']),
• 'C': set(['A', 'F', 'G']),
• 'D': set(['B']),
• 'E': set(['B']),
• 'F': set(['C']),
• 'G': set(['C')}

• def dfs(graph, start, visited=None):


• if visited is None:
• visited = set()
• visited.add(start)
• print(start)
• for next in graph[start] - visited:
• dfs(graph, next, visited)
• return visited

• print("Depth First Search Starting From Vertex A")


• dfs(graph, 'A')

• print("Depth First Search Starting From Vertex G")


• dfs(graph, 'G')
Code Explanation
• First, the graph is defined using a dictionary where each node is a key and its adjacent
nodes are stored in a set.
• The function dfs takes the graph, the starting node, and the goal node as input. It
initializes a visited set to keep track of the visited nodes, a stack to maintain the nodes to
be visited in the future, and a path list to store the visited nodes in the order they are
traversed.
• The starting node is added to the stack and the visited set.
• A while loop is initiated which continues until the stack is empty. Within the loop, the last
element from the stack is popped and stored in a variable called vertex.
• If vertex is equal to the goal node, the function returns the path list containing all the
visited nodes.
• Otherwise, for each of the adjacent nodes of vertex, if they have not been visited yet, they
are added to the stack and the visited set. The current vertex is also added to the path list.
• The function returns None if the goal node is not found.
• Finally just call the function.
Take Aways from DFS
• Key Points:
• Uninformed Search Technique
• Stack(LIF0 approach)
• Deepest Node
• Not Optimal
• Time Complexity: O(b^d) where b stands for
branching factor and d stands depth

You might also like