Bidirectional Search - GeeksforGeeks

CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses
For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more
School Guide
Python Programming
Learn To Make Apps
Explore more
All Courses
TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms
Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data ScienceMachine LearningData Science
Machine Learning
Data Science
CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software DesignsSoftware Design PatternsSystem Design Tutorial
Software Design Patterns
System Design Tutorial
School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
School Programming
MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
JobsApply for JobsPost a JobJOB-A-THON
Apply for Jobs
Post a Job
JOB-A-THON
PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems




WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri
Geeks Digest
Quizzes
Geeks Campus
Gblog Articles
IDE
Campus Mantri
Sign In
Sign In
Home
Saved Videos
Courses


For Working Professionals
                        



LIVE
                        


DSA Live Classes

System Design

Java Backend Development

Full Stack LIVE

Explore More


Self-Paced
                        


DSA- Self Paced

SDE Theory

Must-Do Coding Questions

Explore More


For Students
                        



LIVE
                        


Competitive Programming

Data Structures with C++

Data Science

Explore More


Self-Paced
                        


DSA- Self Paced

CIP

JAVA / Python / C++

Explore More


School Courses
                        


School Guide

Python Programming

Learn To Make Apps

Explore more


Algorithms
                        


Searching Algorithms

Sorting Algorithms

Graph Algorithms

Pattern Searching

Geometric Algorithms

Mathematical

Bitwise Algorithms

Randomized Algorithms

Greedy Algorithms

Dynamic Programming

Divide and Conquer

Backtracking

Branch and Bound

All Algorithms


Analysis of Algorithms
                        


Asymptotic Analysis

Worst, Average and Best Cases

Asymptotic Notations

Little o and little omega notations

Lower and Upper Bound Theory

Analysis of Loops

Solving Recurrences

Amortized Analysis

What does 'Space Complexity' mean ?

Pseudo-polynomial Algorithms

Polynomial Time Approximation Scheme

A Time Complexity Question


Data Structures
                        


Arrays

Linked List

Stack

Queue

Binary Tree

Binary Search Tree

Heap

Hashing

Graph

Advanced Data Structure

Matrix

Strings

All Data Structures


Interview Corner
                        


Company Preparation

Top Topics

Practice Company Questions

Interview Experiences

Experienced Interviews

Internship Interviews

Competititve Programming

Design Patterns

System Design Tutorial

Multiple Choice Quizzes


Languages
                        


C

C++

Java

Python

C#

JavaScript

jQuery

SQL

PHP

Scala

Perl

Go Language

HTML

CSS

Kotlin


ML & Data Science
                        


Machine Learning

Data Science


CS Subjects
                        


Mathematics

Operating System

DBMS

Computer Networks

Computer Organization and Architecture

Theory of Computation

Compiler Design

Digital Logic

Software Engineering


GATE
                        


GATE Computer Science Notes

Last Minute Notes

GATE CS Solved Papers

GATE CS Original Papers and Official Keys

GATE 2021 Dates

GATE CS 2021 Syllabus

Important Topics for GATE CS


Web Technologies
                        


HTML

CSS

JavaScript

AngularJS

ReactJS

NodeJS

Bootstrap

jQuery

PHP


Software Designs
                        


Software Design Patterns

System Design Tutorial


School Learning
                        


School Programming


Mathematics
                        


Number System

Algebra

Trigonometry

Statistics

Probability

Geometry

Mensuration

Calculus


Maths Notes (Class 8-12)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes

Class 12 Notes


NCERT Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


RD Sharma Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Physics Notes (Class 8-11)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes


CS Exams/PSUs
                        



ISRO
                        


ISRO CS Original Papers and Official Keys

ISRO CS Solved Papers

ISRO CS Syllabus for Scientist/Engineer Exam


UGC NET
                        


UGC NET CS Notes Paper II

UGC NET CS Notes Paper III

UGC NET CS Solved Papers


Student
                        


Campus Ambassador Program

School Ambassador Program

Project

Geek of the Month

Campus Geek of the Month

Placement Course

Competititve Programming

Testimonials

Student Chapter

Geek on the Top

Internship

Careers


Curated DSA Lists
                        


Top 50 Array Problems

Top 50 String Problems

Top 50 Tree Problems

Top 50 Graph Problems

Top 50 DP Problems


Tutorials
                        



Jobs
                        


Apply for Jobs

Post a Job

JOB-A-THON


Practice
                        


All DSA Problems

Problem of the Day

Interview Series: Weekly Contests

Bi-Wizard Coding: School Contests

Contests and Events

Practice SDE Sheet


For Working Professionals
                        



LIVE
                        


DSA Live Classes

System Design

Java Backend Development

Full Stack LIVE

Explore More


DSA Live Classes


System Design


Java Backend Development


Full Stack LIVE


Explore More


Self-Paced
                        


DSA- Self Paced

SDE Theory

Must-Do Coding Questions

Explore More


DSA- Self Paced


SDE Theory


Must-Do Coding Questions


Explore More


For Students
                        



LIVE
                        


Competitive Programming

Data Structures with C++

Data Science

Explore More


Competitive Programming


Data Structures with C++


Data Science


Explore More


Self-Paced
                        


DSA- Self Paced

CIP

JAVA / Python / C++

Explore More


DSA- Self Paced


CIP


JAVA / Python / C++


Explore More


School Courses
                        


School Guide

Python Programming

Learn To Make Apps

Explore more


School Guide


Python Programming


Learn To Make Apps


Explore more


Algorithms
                        


Searching Algorithms

Sorting Algorithms

Graph Algorithms

Pattern Searching

Geometric Algorithms

Mathematical

Bitwise Algorithms

Randomized Algorithms

Greedy Algorithms

Dynamic Programming

Divide and Conquer

Backtracking

Branch and Bound

All Algorithms


Searching Algorithms


Sorting Algorithms


Graph Algorithms


Pattern Searching


Geometric Algorithms


Mathematical


Bitwise Algorithms


Randomized Algorithms


Greedy Algorithms


Dynamic Programming


Divide and Conquer


Backtracking


Branch and Bound


All Algorithms


Analysis of Algorithms
                        


Asymptotic Analysis

Worst, Average and Best Cases

Asymptotic Notations

Little o and little omega notations

Lower and Upper Bound Theory

Analysis of Loops

Solving Recurrences

Amortized Analysis

What does 'Space Complexity' mean ?

Pseudo-polynomial Algorithms

Polynomial Time Approximation Scheme

A Time Complexity Question


Asymptotic Analysis


Worst, Average and Best Cases


Asymptotic Notations


Little o and little omega notations


Lower and Upper Bound Theory


Analysis of Loops


Solving Recurrences


Amortized Analysis


What does 'Space Complexity' mean ?


Pseudo-polynomial Algorithms


Polynomial Time Approximation Scheme


A Time Complexity Question


Data Structures
                        


Arrays

Linked List

Stack

Queue

Binary Tree

Binary Search Tree

Heap

Hashing

Graph

Advanced Data Structure

Matrix

Strings

All Data Structures


Arrays


Linked List


Stack


Queue


Binary Tree


Binary Search Tree


Heap


Hashing


Graph


Advanced Data Structure


Matrix


Strings


All Data Structures


Interview Corner
                        


Company Preparation

Top Topics

Practice Company Questions

Interview Experiences

Experienced Interviews

Internship Interviews

Competititve Programming

Design Patterns

System Design Tutorial

Multiple Choice Quizzes


Company Preparation


Top Topics


Practice Company Questions


Interview Experiences


Experienced Interviews


Internship Interviews


Competititve Programming


Design Patterns


System Design Tutorial


Multiple Choice Quizzes


Languages
                        


C

C++

Java

Python

C#

JavaScript

jQuery

SQL

PHP

Scala

Perl

Go Language

HTML

CSS

Kotlin


C


C++


Java


Python


C#


JavaScript


jQuery


SQL


PHP


Scala


Perl


Go Language


HTML


CSS


Kotlin


ML & Data Science
                        


Machine Learning

Data Science


Machine Learning


Data Science


CS Subjects
                        


Mathematics

Operating System

DBMS

Computer Networks

Computer Organization and Architecture

Theory of Computation

Compiler Design

Digital Logic

Software Engineering


Mathematics


Operating System


DBMS


Computer Networks


Computer Organization and Architecture


Theory of Computation


Compiler Design


Digital Logic


Software Engineering


GATE
                        


GATE Computer Science Notes

Last Minute Notes

GATE CS Solved Papers

GATE CS Original Papers and Official Keys

GATE 2021 Dates

GATE CS 2021 Syllabus

Important Topics for GATE CS


GATE Computer Science Notes


Last Minute Notes


GATE CS Solved Papers


GATE CS Original Papers and Official Keys


GATE 2021 Dates


GATE CS 2021 Syllabus


Important Topics for GATE CS


Web Technologies
                        


HTML

CSS

JavaScript

AngularJS

ReactJS

NodeJS

Bootstrap

jQuery

PHP


HTML


CSS


JavaScript


AngularJS


ReactJS


NodeJS


Bootstrap


jQuery


PHP


Software Designs
                        


Software Design Patterns

System Design Tutorial


Software Design Patterns


System Design Tutorial


School Learning
                        


School Programming


School Programming


Mathematics
                        


Number System

Algebra

Trigonometry

Statistics

Probability

Geometry

Mensuration

Calculus


Number System


Algebra


Trigonometry


Statistics


Probability


Geometry


Mensuration


Calculus


Maths Notes (Class 8-12)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes

Class 12 Notes


Class 8 Notes


Class 9 Notes


Class 10 Notes


Class 11 Notes


Class 12 Notes


NCERT Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Class 8 Maths Solution


Class 9 Maths Solution


Class 10 Maths Solution


Class 11 Maths Solution


Class 12 Maths Solution


RD Sharma Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Class 8 Maths Solution


Class 9 Maths Solution


Class 10 Maths Solution


Class 11 Maths Solution


Class 12 Maths Solution


Physics Notes (Class 8-11)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes


Class 8 Notes


Class 9 Notes


Class 10 Notes


Class 11 Notes


CS Exams/PSUs
                        



ISRO
                        


ISRO CS Original Papers and Official Keys

ISRO CS Solved Papers

ISRO CS Syllabus for Scientist/Engineer Exam


ISRO CS Original Papers and Official Keys


ISRO CS Solved Papers


ISRO CS Syllabus for Scientist/Engineer Exam


UGC NET
                        


UGC NET CS Notes Paper II

UGC NET CS Notes Paper III

UGC NET CS Solved Papers


UGC NET CS Notes Paper II


UGC NET CS Notes Paper III


UGC NET CS Solved Papers


Student
                        


Campus Ambassador Program

School Ambassador Program

Project

Geek of the Month

Campus Geek of the Month

Placement Course

Competititve Programming

Testimonials

Student Chapter

Geek on the Top

Internship

Careers


Campus Ambassador Program


School Ambassador Program


Project


Geek of the Month


Campus Geek of the Month


Placement Course


Competititve Programming


Testimonials


Student Chapter


Geek on the Top


Internship


Careers


Curated DSA Lists
                        


Top 50 Array Problems

Top 50 String Problems

Top 50 Tree Problems

Top 50 Graph Problems

Top 50 DP Problems


Top 50 Array Problems


Top 50 String Problems


Top 50 Tree Problems


Top 50 Graph Problems


Top 50 DP Problems


Tutorials
                        



Jobs
                        


Apply for Jobs

Post a Job

JOB-A-THON


Apply for Jobs


Post a Job


JOB-A-THON


Practice
                        


All DSA Problems

Problem of the Day

Interview Series: Weekly Contests

Bi-Wizard Coding: School Contests

Contests and Events

Practice SDE Sheet


All DSA Problems


Problem of the Day


Interview Series: Weekly Contests


Bi-Wizard Coding: School Contests


Contests and Events


Practice SDE Sheet

GBlog
Puzzles
What's New ?
Array
Matrix
Strings
Hashing
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Graph
Searching
Sorting
Divide & Conquer
Mathematical
Geometric
Bitwise
Greedy
Backtracking
Branch and Bound
Dynamic Programming
Pattern Searching
Randomized
Print all paths from a given source to a destination
Print all paths from a given source to a destination using BFS
Minimum number of edges between two vertices of a Graph
Count nodes within K-distance from all nodes in a set
Bidirectional Search
Minimum edge reversals to make a root
BFS for Disconnected Graph
N Queen Problem | Backtracking-3
Printing all solutions in N-Queen Problem
Warnsdorff’s algorithm for Knight’s tour problem
The Knight’s tour problem | Backtracking-1
Rat in a Maze | Backtracking-2
Count number of ways to reach destination in a Maze
Count all possible paths from top left to bottom right of a mXn matrix
Print all possible paths from top left to bottom right of a mXn matrix
Unique paths in a Grid with Obstacles
Unique paths covering every non-obstacle block exactly once in a grid
Depth First Search or DFS for a Graph
Breadth First Search or BFS for a Graph
Level Order Binary Tree Traversal
Tree Traversals (Inorder, Preorder and Postorder)
Inorder Tree Traversal without Recursion
Inorder Tree Traversal without recursion and without stack!
Print Postorder traversal from given Inorder and Preorder traversals
Construct Tree from given Inorder and Preorder traversals
Dijkstra's shortest path algorithm | Greedy Algo-7
Graph and its representations
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Print all paths from a given source to a destination
Print all paths from a given source to a destination using BFS
Minimum number of edges between two vertices of a Graph
Count nodes within K-distance from all nodes in a set
Bidirectional Search
Minimum edge reversals to make a root
BFS for Disconnected Graph
N Queen Problem | Backtracking-3
Printing all solutions in N-Queen Problem
Warnsdorff’s algorithm for Knight’s tour problem
The Knight’s tour problem | Backtracking-1
Rat in a Maze | Backtracking-2
Count number of ways to reach destination in a Maze
Count all possible paths from top left to bottom right of a mXn matrix
Print all possible paths from top left to bottom right of a mXn matrix
Unique paths in a Grid with Obstacles
Unique paths covering every non-obstacle block exactly once in a grid
Depth First Search or DFS for a Graph
Breadth First Search or BFS for a Graph
Level Order Binary Tree Traversal
Tree Traversals (Inorder, Preorder and Postorder)
Inorder Tree Traversal without Recursion
Inorder Tree Traversal without recursion and without stack!
Print Postorder traversal from given Inorder and Preorder traversals
Construct Tree from given Inorder and Preorder traversals
Dijkstra's shortest path algorithm | Greedy Algo-7
Graph and its representations
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Difficulty Level :
Hard
Searching a graph is quite famous problem and have a lot of practical use. We have already discussed here how to search for a goal vertex starting from a source vertex using BFS. In normal graph search using BFS/DFS we begin our search in one direction usually from source vertex toward the goal vertex, but what if we start search from both direction simultaneously.Bidirectional search is a graph search algorithm which find smallest path from source to goal vertex. It runs two simultaneous search – 
Forward search from source/initial vertex toward goal vertexBackward search from goal/target vertex toward source vertex
Forward search from source/initial vertex toward goal vertex
Backward search from goal/target vertex toward source vertex
Bidirectional search replaces single search graph(which is likely to grow exponentially) with two smaller sub graphs – one starting from initial vertex and other starting from goal vertex. The search terminates when two graphs intersect.Just like A* algorithm, bidirectional search can be guided by a heuristic estimate of remaining distance from source to goal and vice versa for finding shortest path possible.Consider following simple example-  
Suppose we want to find if there exists a path from vertex 0 to vertex 14. Here we can execute two searches, one from vertex 0 and other from vertex 14. When both forward and backward search meet at vertex 7, we know that we have found a path from node 0 to 14 and search can be terminated now. We can clearly see that we have successfully avoided unnecessary exploration.  
Why bidirectional approach?
Because in many cases it is faster, it dramatically reduce the amount of required exploration. Suppose if branching factor of tree is b and distance of goal vertex from source is d, then the normal BFS/DFS searching complexity would be O(bd). On the other hand, if we execute two search operation then the complexity would be O(bd/2) for each search and total complexity would be O(bd/2 +bd/2) which is far less than O(bd).
When to use bidirectional approach?
We can consider bidirectional approach when- 
Both initial and goal states are unique and completely defined.The branching factor is exactly the same in both directions.
Both initial and goal states are unique and completely defined.
The branching factor is exactly the same in both directions.
Performance measures
Completeness : Bidirectional search is complete if BFS is used in both searches.
Optimality : It is optimal if BFS is used for search and paths have uniform cost.
Time and Space Complexity : Time and space complexity is O(bd/2).
Below is very simple implementation representing the concept of bidirectional search using BFS. This implementation considers undirected paths without any weight. 
C++
Python3
// C++ program for Bidirectional BFS search// to check path between two vertices#include <bits/stdc++.h>using namespace std; // class representing undirected graph// using adjacency listclass Graph{    //number of nodes in graph    int V;     // Adjacency list    list<int> *adj;public:    Graph(int V);    int isIntersecting(bool *s_visited, bool *t_visited);    void addEdge(int u, int v);    void printPath(int *s_parent, int *t_parent, int s,                             int t, int intersectNode);    void BFS(list<int> *queue, bool *visited, int *parent);    int biDirSearch(int s, int t);}; Graph::Graph(int V){    this->V = V;    adj = new list<int>[V];}; // Method for adding undirected edgevoid Graph::addEdge(int u, int v){    this->adj[u].push_back(v);    this->adj[v].push_back(u);}; // Method for Breadth First Searchvoid Graph::BFS(list<int> *queue, bool *visited,                                    int *parent){    int current = queue->front();    queue->pop_front();    list<int>::iterator i;    for (i=adj[current].begin();i != adj[current].end();i++)    {        // If adjacent vertex is not visited earlier        // mark it visited by assigning true value        if (!visited[*i])        {            // set current as parent of this vertex            parent[*i] = current;             // Mark this vertex visited            visited[*i] = true;             // Push to the end of queue            queue->push_back(*i);        }    }}; // check for intersecting vertexint Graph::isIntersecting(bool *s_visited, bool *t_visited){    int intersectNode = -1;    for(int i=0;i<V;i++)    {        // if a vertex is visited by both front        // and back BFS search return that node        // else return -1        if(s_visited[i] && t_visited[i])            return i;    }    return -1;}; // Print the path from source to targetvoid Graph::printPath(int *s_parent, int *t_parent,                  int s, int t, int intersectNode){    vector<int> path;    path.push_back(intersectNode);    int i = intersectNode;    while (i != s)    {        path.push_back(s_parent[i]);        i = s_parent[i];    }    reverse(path.begin(), path.end());    i = intersectNode;    while(i != t)    {        path.push_back(t_parent[i]);        i = t_parent[i];    }     vector<int>::iterator it;    cout<<"*****Path*****\n";    for(it = path.begin();it != path.end();it++)        cout<<*it<<" ";    cout<<"\n";}; // Method for bidirectional searchingint Graph::biDirSearch(int s, int t){    // boolean array for BFS started from    // source and target(front and backward BFS)    // for keeping track on visited nodes    bool s_visited[V], t_visited[V];     // Keep track on parents of nodes    // for front and backward search    int s_parent[V], t_parent[V];     // queue for front and backward search    list<int> s_queue, t_queue;     int intersectNode = -1;     // necessary initialization    for(int i=0; i<V; i++)    {        s_visited[i] = false;        t_visited[i] = false;    }     s_queue.push_back(s);    s_visited[s] = true;     // parent of source is set to -1    s_parent[s]=-1;     t_queue.push_back(t);    t_visited[t] = true;     // parent of target is set to -1    t_parent[t] = -1;     while (!s_queue.empty() && !t_queue.empty())    {        // Do BFS from source and target vertices        BFS(&s_queue, s_visited, s_parent);        BFS(&t_queue, t_visited, t_parent);         // check for intersecting vertex        intersectNode = isIntersecting(s_visited, t_visited);         // If intersecting vertex is found        // that means there exist a path        if(intersectNode != -1)        {            cout << "Path exist between " << s << " and "                 << t << "\n";            cout << "Intersection at: " << intersectNode << "\n";             // print the path and exit the program            printPath(s_parent, t_parent, s, t, intersectNode);            exit(0);        }    }    return -1;} // Driver codeint main(){    // no of vertices in graph    int n=15;     // source vertex    int s=0;     // target vertex    int t=14;     // create a graph given in above diagram    Graph g(n);    g.addEdge(0, 4);    g.addEdge(1, 4);    g.addEdge(2, 5);    g.addEdge(3, 5);    g.addEdge(4, 6);    g.addEdge(5, 6);    g.addEdge(6, 7);    g.addEdge(7, 8);    g.addEdge(8, 9);    g.addEdge(8, 10);    g.addEdge(9, 11);    g.addEdge(9, 12);    g.addEdge(10, 13);    g.addEdge(10, 14);    if (g.biDirSearch(s, t) == -1)        cout << "Path don't exist between "             << s << " and " << t << "\n";     return 0;}
# Python3 program for Bidirectional BFS# Search to check path between two vertices # Class definition for node to# be added to graphclass AdjacentNode:         def __init__(self, vertex):                 self.vertex = vertex        self.next = None # BidirectionalSearch implementationclass BidirectionalSearch:         def __init__(self, vertices):                 # Initialize vertices and        # graph with vertices        self.vertices = vertices        self.graph = [None] * self.vertices                 # Initializing queue for forward        # and backward search        self.src_queue = list()        self.dest_queue = list()                 # Initializing source and        # destination visited nodes as False        self.src_visited = [False] * self.vertices        self.dest_visited = [False] * self.vertices                 # Initializing source and destination        # parent nodes        self.src_parent = [None] * self.vertices        self.dest_parent = [None] * self.vertices             # Function for adding undirected edge    def add_edge(self, src, dest):                 # Add edges to graph                 # Add source to destination        node = AdjacentNode(dest)        node.next = self.graph[src]        self.graph[src] = node         # Since graph is undirected add        # destination to source        node = AdjacentNode(src)        node.next = self.graph[dest]        self.graph[dest] = node             # Function for Breadth First Search    def bfs(self, direction = 'forward'):                 if direction == 'forward':                         # BFS in forward direction            current = self.src_queue.pop(0)            connected_node = self.graph[current]                         while connected_node:                vertex = connected_node.vertex                                 if not self.src_visited[vertex]:                    self.src_queue.append(vertex)                    self.src_visited[vertex] = True                    self.src_parent[vertex] = current                                     connected_node = connected_node.next        else:                         # BFS in backward direction            current = self.dest_queue.pop(0)            connected_node = self.graph[current]                         while connected_node:                vertex = connected_node.vertex                                 if not self.dest_visited[vertex]:                    self.dest_queue.append(vertex)                    self.dest_visited[vertex] = True                    self.dest_parent[vertex] = current                                     connected_node = connected_node.next                     # Check for intersecting vertex    def is_intersecting(self):                 # Returns intersecting node        # if present else -1        for i in range(self.vertices):            if (self.src_visited[i] and                self.dest_visited[i]):                return i                         return -1     # Print the path from source to target    def print_path(self, intersecting_node,                   src, dest):                                # Print final path from        # source to destination        path = list()        path.append(intersecting_node)        i = intersecting_node                 while i != src:            path.append(self.src_parent[i])            i = self.src_parent[i]                     path = path[::-1]        i = intersecting_node                 while i != dest:            path.append(self.dest_parent[i])            i = self.dest_parent[i]                     print("*****Path*****")        path = list(map(str, path))                 print(' '.join(path))         # Function for bidirectional searching    def bidirectional_search(self, src, dest):                 # Add source to queue and mark        # visited as True and add its        # parent as -1        self.src_queue.append(src)        self.src_visited[src] = True        self.src_parent[src] = -1                 # Add destination to queue and        # mark visited as True and add        # its parent as -1        self.dest_queue.append(dest)        self.dest_visited[dest] = True        self.dest_parent[dest] = -1         while self.src_queue and self.dest_queue:                         # BFS in forward direction from            # Source Vertex            self.bfs(direction = 'forward')                         # BFS in reverse direction            # from Destination Vertex            self.bfs(direction = 'backward')                         # Check for intersecting vertex            intersecting_node = self.is_intersecting()                         # If intersecting vertex exists            # then path from source to            # destination exists            if intersecting_node != -1:                print(f"Path exists between {src} and {dest}")                print(f"Intersection at : {intersecting_node}")                self.print_path(intersecting_node,                                src, dest)                exit(0)        return -1 # Driver codeif __name__ == '__main__':         # Number of Vertices in graph    n = 15         # Source Vertex    src = 0         # Destination Vertex    dest = 14         # Create a graph    graph = BidirectionalSearch(n)    graph.add_edge(0, 4)    graph.add_edge(1, 4)    graph.add_edge(2, 5)    graph.add_edge(3, 5)    graph.add_edge(4, 6)    graph.add_edge(5, 6)    graph.add_edge(6, 7)    graph.add_edge(7, 8)    graph.add_edge(8, 9)    graph.add_edge(8, 10)    graph.add_edge(9, 11)    graph.add_edge(9, 12)    graph.add_edge(10, 13)    graph.add_edge(10, 14)         out = graph.bidirectional_search(src, dest)         if out == -1:        print(f"Path does not exist between {src} and {dest}") # This code is contributed by Nirjhari Jankar
Output: 
Path exist between 0 and 14
Intersection at: 7
*****Path*****
0 4 6 7 8 10 14 
References 
https://en.wikipedia.org/wiki/Bidirectional_search
This article is contributed by Atul Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
nirjhari jankar
prathibar03
BFS
Graph
Graph
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Topological Sorting
Bellman–Ford Algorithm | DP-23
Detect Cycle in a Directed Graph
Floyd Warshall Algorithm | DP-16
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Ford-Fulkerson Algorithm for Maximum Flow Problem
Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
Strongly Connected Components
Detect cycle in an undirected graph