Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Data Science
  • Data Science Projects
  • Data Analysis
  • Data Visualization
  • Machine Learning
  • ML Projects
  • Deep Learning
  • NLP
  • Computer Vision
  • Artificial Intelligence
Open In App
Next Article:
Uninformed Search Algorithms in AI
Next article icon

Search Algorithms in AI

Last Updated : 22 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 State. 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.

Types of search algorithms: 

There are far too many powerful search algorithms out there to fit in a single article. Instead, this article will discuss six of the fundamental search algorithms, divided into two categories, as shown below. 

Categories of search algorithms in AI

Note that there is much more to search algorithms than the chart I have provided above. However, this article will mostly stick to the above chart, exploring the algorithms given there. 

Uninformed Search Algorithms: 

The search algorithms in this section have no additional information on the goal node other than the one provided in the problem definition. The plans to reach the goal state from the start state differ only by the order and/or length of actions. Uninformed search is also called Blind search. These algorithms can only generate the successors and differentiate between the goal state and non goal state. 

The following uninformed search algorithms are discussed in this section.

  1. Depth First Search
  2. Breadth First Search
  3. Uniform Cost Search

Each of these algorithms will have: 

  • A problem graph, containing the start node S and the goal node G.
  • A strategy, describing the manner in which the graph will be traversed to get to G.
  • A fringe, which is a data structure used to store all the possible states (nodes) that you can go from the current states.
  • A tree, that results while traversing to the goal node.
  • A solution plan, which the sequence of nodes from S to G.

Depth First Search:

Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data structures. The algorithm starts at the root node (selecting some arbitrary node as the root node in the case of a graph) and explores as far as possible along each branch before backtracking. It uses last in- first-out strategy and hence it is implemented using a stack.

Example: 

Question. Which solution would DFS find to move from node S to node G if run on the graph below? 
 

DFS ques

Solution. The equivalent search tree for the above graph is as follows. As DFS traverses the tree "deepest node first", it would always pick the deeper branch until it reaches the solution (or it runs out of nodes, and goes to the next branch). The traversal is shown in blue arrows. 

DFS soln

Path:   S -> A -> B -> C -> G 


d        = the depth of the search tree = the number of levels of the search tree. 
n^i        = number of nodes in level i        . 

Time complexity: Equivalent to the number of nodes traversed in DFS. T(n) = 1 + n^2 + n^3 + ... + n^d = O(n^d)        
Space complexity: Equivalent to how large can the fringe get. S(n) = O(n \times d)        
Completeness: DFS is complete if the search tree is finite, meaning for a given finite search tree, DFS will come up with a solution if it exists. 
Optimality: DFS is not optimal, meaning the number of steps in reaching the solution, or the cost spent in reaching it is high. 

Breadth First Search:

Breadth-first search (BFS) is an algorithm for traversing or searching tree or graph data structures. It starts at the tree root (or some arbitrary node of a graph, sometimes referred to as a 'search key'), and explores all of the neighbor nodes at the present depth prior to moving on to the nodes at the next depth level. It is implemented using a queue.

Example: 
Question. Which solution would BFS find to move from node S to node G if run on the graph below? 

BFS ques

Solution. The equivalent search tree for the above graph is as follows. As BFS traverses the tree "shallowest node first", it would always pick the shallower branch until it reaches the solution (or it runs out of nodes, and goes to the next branch). The traversal is shown in blue arrows. 

BFS solution

Path: S -> D -> G 

 s        = the depth of the shallowest solution. 
n^i        = number of nodes in level i        . 
Time complexity: Equivalent to the number of nodes traversed in BFS until the shallowest solution. T(n) = 1 + n^2 + n^3 + ... + n^s = O(n^s)        
Space complexity: Equivalent to how large can the fringe get. S(n) = O(n^s)        
Completeness: BFS is complete, meaning for a given search tree, BFS will come up with a solution if it exists. 

Optimality: BFS is optimal as long as the costs of all edges are equal. 

Uniform Cost Search: 

UCS is different from BFS and DFS because here the costs come into play. In other words, traversing via different edges might not have the same cost. The goal is to find a path where the cumulative sum of costs is the least. 

Cost of a node is defined as: 

  cost(node) = cumulative cost of all nodes from root   cost(root) = 0

Example: 
Question. Which solution would UCS find to move from node S to node G if run on the graph below? 

UCS problem

Solution. The equivalent search tree for the above graph is as follows. The cost of each node is the cumulative cost of reaching that node from the root. Based on the UCS strategy, the path with the least cumulative cost is chosen. Note that due to the many options in the fringe, the algorithm explores most of them so long as their cost is low, and discards them when a lower-cost path is found; these discarded traversals are not shown below. The actual traversal is shown in blue. 

UCS solution

Path: S -> A -> B -> G 
Cost: 5 

Let C        = cost of solution. 
\varepsilon        = arcs cost. 

Then C / \varepsilon =        effective depth 

Time complexity:   T(n) = O(n^C ^/ ^\varepsilon)        , Space complexity:   S(n) = O(n^C ^/ ^\varepsilon)       

Advantages: 

  • UCS is complete only if states are finite and there should be no loop with zero weight.
  • UCS is optimal only if there is no negative cost.

Disadvantages: 

  • Explores options in every "direction".
  • No information on goal location.

Informed Search Algorithms: 

Here, the algorithms have information on the goal state, which helps in more efficient searching. This information is obtained by something called a heuristic. 
In this section, we will discuss the following search algorithms. 

  1. Greedy Search
  2. A* Tree Search
  3. A* Graph Search

Search Heuristics: In an informed search, a heuristic is a function that estimates how close a state is to the goal state. For example - Manhattan distance, Euclidean distance, etc. (Lesser the distance, closer the goal.) Different heuristics are used in different informed algorithms discussed below. 

Greedy Search:

In greedy search, we expand the node closest to the goal node. The "closeness" is estimated by a heuristic h(x). 

Heuristic: A heuristic h is defined as- 
h(x) = Estimate of distance of node x from the goal node. 
Lower the value of h(x), closer is the node from the goal. 

Strategy: Expand the node closest to the goal state, i.e. expand the node with a lower h value. 

Example: 

Question. Find the path from S to G using greedy search. The heuristic values h of each node below the name of the node. 
 

greedy algo ques

Solution. Starting from S, we can traverse to A(h=9) or D(h=5). We choose D, as it has the lower heuristic cost. Now from D, we can move to B(h=4) or E(h=3). We choose E with a lower heuristic cost. Finally, from E, we go to G(h=0). This entire traversal is shown in the search tree below, in blue. 

greedy solution


Path:   S -> D -> E -> G 

Advantage: Works well with informed search problems, with fewer steps to reach a goal. 
Disadvantage: Can turn into unguided DFS in the worst case. 
 

A* Tree Search:

A* Tree Search, or simply known as A* Search, combines the strengths of uniform-cost search and greedy search. In this search, the heuristic is the summation of the cost in UCS, denoted by g(x), and the cost in the greedy search, denoted by h(x). The summed cost is denoted by f(x). 

Heuristic: The following points should be noted wrt heuristics in A* search. f(x) = g(x) + h(x) 

  • Here, h(x) is called the forward cost and is an estimate of the distance of the current node from the goal node.
  • And, g(x) is called the backward cost and is the cumulative cost of a node from the root node.
  • A* search is optimal only when for all nodes, the forward cost for a node h(x) underestimates the actual cost h*(x) to reach the goal. This property of A* heuristic is called admissibility. 
Admissibility:   0 \leqslant h(x) \leqslant h^*(x) 


Strategy: Choose the node with the lowest f(x) value. 

Example: 

Question. Find the path to reach from S to G using A* search. 

a* question

Solution. Starting from S, the algorithm computes g(x) + h(x) for all nodes in the fringe at each step, choosing the node with the lowest sum. The entire work is shown in the table below. 

Note that in the fourth set of iterations, we get two paths with equal summed cost f(x), so we expand them both in the next set. The path with a lower cost on further expansion is the chosen path. 
 

Pathh(x)g(x)f(x)
S707
    
S -> A9312
S -> D   ✔527
    
S -> D -> B   ✔42 + 1 = 37
S -> D -> E32 + 4 = 69
    
S -> D -> B -> C   ✔23 + 2 = 57
S -> D -> B -> E   ✔33 + 1 = 47
    
S -> D -> B -> C -> G05 + 4 = 99
S -> D -> B -> E -> G   ✔ 04 + 3 = 77

Path:   S -> D -> B -> E -> G 
Cost:   7 
 

A* Graph Search:

  • A* tree search works well, except that it takes time re-exploring the branches it has already explored. In other words, if the same node has expanded twice in different branches of the search tree, A* search might explore both of those branches, thus wasting time
  • A* Graph Search, or simply Graph Search, removes this limitation by adding this rule: do not expand the same node more than once. 
  • Heuristic. Graph search is optimal only when the forward cost between two successive nodes A and B, given by h(A) - h (B), is less than or equal to the backward cost between those two nodes g(A -> B). This property of the graph search heuristic is called consistency. 
Consistency:   h(A) - h(B) \leqslant g(A \to B) 

Example:

Question. Use graph searches to find paths from S to G in the following graph. 

graph search question


the Solution. We solve this question pretty much the same way we solved last question, but in this case, we keep a track of nodes explored so that we don't re-explore them. 

Path:   S -> D -> B -> E -> G 
Cost:   7 


Next Article
Uninformed Search Algorithms in AI

M

MdRafiAkhtar
Improve
Article Tags :
  • Technical Scripter
  • Machine Learning
Practice Tags :
  • Machine Learning

Similar Reads

    Artificial Intelligence Tutorial | AI Tutorial
    Artificial Intelligence (AI) refers to the simulation of human intelligence in machines which helps in allowing them to think and act like humans. It involves creating algorithms and systems that can perform tasks which requiring human abilities such as visual perception, speech recognition, decisio
    5 min read
    What is Artificial Intelligence(AI)?
    Artificial Intelligence (AI) refers to the technology that allows machines and computers to replicate human intelligence. It enables systems to perform tasks that require human-like decision-making, such as learning from data, identifying patterns, making informed choices and solving complex problem
    13 min read
    History of AI
    The term Artificial Intelligence (AI) is already widely used in everything from smartphones to self-driving cars. AI has come a long way from science fiction stories to practical uses. Yet What is artificial intelligence and how did it go from being an idea in science fiction to a technology that re
    7 min read

    Types of AI

    Types of Artificial Intelligence (AI)
    Artificial Intelligence refers to something which is made by humans or non-natural things and Intelligence means the ability to understand or think. AI is not a system but it is implemented in the system. There are many different types of AI, each with its own strengths and weaknesses.This article w
    6 min read
    Types of AI Based on Capabilities: An In-Depth Exploration
    Artificial Intelligence (AI) is not just a single entity but encompasses a wide range of systems and technologies with varying levels of capabilities. To understand the full potential and limitations of AI, it's important to categorize it based on its capabilities. This article delves into the diffe
    5 min read
    Types of AI Based on Functionalities
    Artificial Intelligence (AI) has become an integral part of modern technology, influencing everything from how we interact with our devices to how businesses operate. However, AI is not a monolithic concept; it can be classified into different types based on its functionalities. Understanding these
    7 min read
    Agents in AI
    An AI agent is a software program that can interact with its surroundings, gather information, and use that information to complete tasks on its own to achieve goals set by humans.For instance, an AI agent on an online shopping platform can recommend products, answer customer questions, and process
    9 min read

    Problem Solving in AI

    Search Algorithms in AI
    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.
    10 min read
    Uninformed Search Algorithms in AI
    Uninformed search algorithms is also known as blind search algorithms, are a class of search algorithms that do not use any domain-specific knowledge about the problem being solved. Uninformed search algorithms rely on the information provided in the problem definition, such as the initial state, ac
    8 min read
    Informed Search Algorithms in Artificial Intelligence
    Informed search algorithms, also known as heuristic search algorithms, are an essential component of Artificial Intelligence (AI). These algorithms use domain-specific knowledge to improve the efficiency of the search process, leading to faster and more optimal solutions compared to uninformed searc
    10 min read
    Local Search Algorithm in Artificial Intelligence
    Local search algorithms are essential tools in artificial intelligence and optimization, employed to find high-quality solutions in large and complex problem spaces. Key algorithms include Hill-Climbing Search, Simulated Annealing, Local Beam Search, Genetic Algorithms, and Tabu Search. Each of thes
    4 min read
    Adversarial Search Algorithms in Artificial Intelligence (AI)
    Adversarial search algorithms are the backbone of strategic decision-making in artificial intelligence, it enables the agents to navigate competitive scenarios effectively. This article offers concise yet comprehensive advantages of these algorithms from their foundational principles to practical ap
    15+ min read
    Constraint Satisfaction Problems (CSP) in Artificial Intelligence
    A Constraint Satisfaction Problem is a mathematical problem where the solution must meet a number of constraints. In CSP the objective is to assign values to variables such that all the constraints are satisfied. Many AI applications use CSPs to solve decision-making problems that involve managing o
    10 min read

    Knowledge, Reasoning and Planning in AI

    How do knowledge representation and reasoning techniques support intelligent systems?
    In artificial intelligence (AI), knowledge representation and reasoning (KR&R) stands as a fundamental pillar, crucial for enabling machines to emulate complex decision-making and problem-solving abilities akin to those of humans. This article explores the intricate relationship between KR&R
    5 min read
    First-Order Logic in Artificial Intelligence
    First-order logic (FOL) is also known as predicate logic. It is a foundational framework used in mathematics, philosophy, linguistics, and computer science. In artificial intelligence (AI), FOL is important for knowledge representation, automated reasoning, and NLP.FOL extends propositional logic by
    3 min read
    Types of Reasoning in Artificial Intelligence
    In today's tech-driven world, machines are being designed to mimic human intelligence and actions. One key aspect of this is reasoning, a logical process that enables machines to conclude, make predictions, and solve problems just like humans. Artificial Intelligence (AI) employs various types of re
    6 min read
    What is the Role of Planning in Artificial Intelligence?
    Artificial Intelligence (AI) is reshaping the future, playing a pivotal role in domains like intelligent robotics, self-driving cars, and smart cities. At the heart of AI systems’ ability to perform tasks autonomously is AI planning, which is critical in guiding AI systems to make informed decisions
    7 min read
    Representing Knowledge in an Uncertain Domain in AI
    Artificial Intelligence (AI) systems often operate in environments where uncertainty is a fundamental aspect. Representing and reasoning about knowledge in such uncertain domains is crucial for building robust and intelligent systems. This article explores the various methods and techniques used in
    6 min read

    Learning in AI

    Supervised Machine Learning
    Supervised machine learning is a fundamental approach for machine learning and artificial intelligence. It involves training a model using labeled data, where each input comes with a corresponding correct output. The process is like a teacher guiding a student—hence the term "supervised" learning. I
    12 min read
    What is Unsupervised Learning?
    Unsupervised learning is a branch of machine learning that deals with unlabeled data. Unlike supervised learning, where the data is labeled with a specific category or outcome, unsupervised learning algorithms are tasked with finding patterns and relationships within the data without any prior knowl
    8 min read
    Semi-Supervised Learning in ML
    Today's Machine Learning algorithms can be broadly classified into three categories, Supervised Learning, Unsupervised Learning, and Reinforcement Learning. Casting Reinforced Learning aside, the primary two categories of Machine Learning problems are Supervised and Unsupervised Learning. The basic
    4 min read
    Reinforcement Learning
    Reinforcement Learning (RL) is a branch of machine learning that focuses on how agents can learn to make decisions through trial and error to maximize cumulative rewards. RL allows machines to learn by interacting with an environment and receiving feedback based on their actions. This feedback comes
    6 min read
    Self-Supervised Learning (SSL)
    In this article, we will learn a major type of machine learning model which is Self-Supervised Learning Algorithms. Usage of these algorithms has increased widely in the past times as the sizes of the model have increased up to billions of parameters and hence require a huge corpus of data to train
    8 min read
    Introduction to Deep Learning
    Deep Learning is transforming the way machines understand, learn and interact with complex data. Deep learning mimics neural networks of the human brain, it enables computers to autonomously uncover patterns and make informed decisions from vast amounts of unstructured data. How Deep Learning Works?
    7 min read
    Natural Language Processing (NLP) - Overview
    Natural Language Processing (NLP) is a field that combines computer science, artificial intelligence and language studies. It helps computers understand, process and create human language in a way that makes sense and is useful. With the growing amount of text data from social media, websites and ot
    9 min read
    Computer Vision Tutorial
    Computer Vision is a branch of Artificial Intelligence (AI) that enables computers to interpret and extract information from images and videos, similar to human perception. It involves developing algorithms to process visual data and derive meaningful insights.Why Learn Computer Vision?High Demand i
    8 min read
    Artificial Intelligence in Robotics
    Artificial Intelligence (AI) in robotics is one of the most groundbreaking technological advancements, revolutionizing how robots perform tasks. What was once a futuristic concept from space operas, the idea of "artificial intelligence robots" is now a reality, shaping industries globally. Unlike ea
    10 min read

    Generative AI

    Generative Adversarial Network (GAN)
    Generative Adversarial Networks (GANs) help machines to create new, realistic data by learning from existing examples. It is introduced by Ian Goodfellow and his team in 2014 and they have transformed how computers generate images, videos, music and more. Unlike traditional models that only recogniz
    12 min read
    Variational AutoEncoders
    Variational Autoencoders (VAEs) are type of generative model in machine learning that create new data similar to the input they are trained on. They not only compress and reconstruct data like traditional autoencoders but also learn a continuous probabilistic representation of the underlying feature
    7 min read
    What are Diffusion Models?
    Diffusion models are a powerful class of generative models that have gained prominence in the field of machine learning and artificial intelligence. They offer a unique approach to generating data by simulating the diffusion process, which is inspired by physical processes such as heat diffusion. Th
    6 min read
    Transformers in Machine Learning
    Transformer is a neural network architecture used for performing machine learning tasks particularly in natural language processing (NLP) and computer vision. In 2017 Vaswani et al. published a paper " Attention is All You Need" in which the transformers architecture was introduced. The article expl
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences