You are on page 1of 3

Breadth First Search (BFS) Algorithm :

Explanation :
 This code represents the Breadth-First Search algorithm. Here's a breakdown of
what each part does:
 Initialization: It initializes a node with the initial state of the problem and sets
the path cost to 0.
 Goal Test: It checks if the initial state is already a goal state. If so, it returns the
solution.
 Frontier: It initializes a FIFO queue (first-in, first-out) called frontier with the
initial node.
 Explored set: It initializes an empty set called explored to keep track of the
states that have already been explored.
 Main Loop: The algorithm runs in a loop until either a solution is found or the
frontier becomes empty.
 Expanding nodes: It pops a node from the frontier (FIFO, so it picks the
shallowest node) and adds its state to the explored set.
 Goal Test (child): It checks if the popped node is a goal state. If so, it returns
the solution.
 Child Nodes Generation: It generates child nodes by applying actions available
in the problem to the current node's state.
 Child Nodes Check: It checks if the child node's state is not already explored or
in the frontier. If not, it adds the child node to the frontier.
 Here's a brief explanation of each function used:
 POP(frontier): Removes and returns the node at the front of the queue.
 INSERT(child, frontier): Inserts the child node into the frontier queue.
 problem.GOAL-TEST(state): Checks whether the given state is a goal state.
 problem.ACTIONS(state): Returns a list of actions that can be executed in the
given state.
 CHILD-NODE(problem, node, action): Generates a child node by applying the
given action to the parent node.
 This algorithm systematically explores all possible states in a breadth-first
manner until it finds a goal state or exhausts all possibilities without
finding a solution.
Example

 The root node is expanded first and then all the successors of the nodes
are expended next, and their successors and so on.
 In general, all the nodes at a given depth are expanded in the search three
before any node at next level are expanded.
 Mark any node as start(initial) node
 explore and traverse un-visited nodes adjacent to starting node
 mark nodes as completed and move to next adjacent and un-visited node.

Completeness : yes (if b is finite),the shallowest solution is returned


Time complexity : b+b2+b3+….+bd=O(bd)
time requirement is still a major factor
space complexity : O(bd) (keeps every node in memory)
space is the bigger problem (more than time)
optimal : yes if step costs are all identical or path cost is a nondecreasing
function of the depth of the node.
Example 2:

Steps to solve:

1. 2.

3. 4.

5. 6.

7.

You might also like