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 uses the opposite strategy as depth-first searchwhich instead explores the node branch as far as possible before being forced to backtrack and expand other nodes. BFS and its application in finding connected components of graphs were invented in by Konrad Zusein his rejected Ph.
Moorewho used it to find the shortest path out of a maze,   and later developed by C. Lee into a wire routing algorithm published Input : A graph Graph and a starting vertex root of Graph.
Output : Goal state. The parent links trace the shortest path back to root. This non-recursive implementation is similar to the non-recursive implementation of depth-first searchbut differs from it in two ways:. Nodes can be labelled as discovered by storing them in a set, or by an attribute on each node, depending on the implementation. The parent attribute of each node is useful for accessing the nodes in a shortest path, for example by backtracking from the destination node up to the starting node, once the BFS has been run, and the predecessors nodes have been set.
Breadth-first search produces a so-called breadth first tree. You can see how a breadth first tree looks in the following example. The following is an example of the breadth-first tree obtained by running a BFS on German cities starting from Frankfurt :. This is in addition to the space required for the graph itself, which may vary depending on the graph representation used by an implementation of the algorithm.
In the analysis of algorithms, the input to breadth-first search is assumed to be a finite graph, represented explicitly as an adjacency list or similar representation. However, in the application of graph traversal methods in artificial intelligence the input may be an implicit representation of an infinite graph. In this context, a search method is described as being complete if it is guaranteed to find a goal state if one exists.
Computer Science Stack Exchange is a question and answer site for students, researchers and practitioners of computer science. It only takes a minute to sign up. I'm in a data structures course, but our current unit discusses recursion and not data structures, and I need to implement breadth-first recursion for the purpose of finding the shortest path through a maze.
Breadth First Search or BFS for a Graph
Is there a way to do this just using the basic structure of recursive calls and base cases? Or will I need data structures such as queues or stacks to implement breadth-first recursion? You basically have two choices: "cheating" by embedding a queue in the nodes, and simulating BFS with higher complexity. If you look at virtually any description of BFS, e. So, even if you aren't allowed to use some clearly-cut external queue data structure, you can easily embed one using node attributes:.
It's possible to run BFS recursively without any data structures, but with higher complexity. Then we could write the following variation of BFS:. Besides such cheap tricks, you cannot run BFS, as it uses a queue, and not a stack. Say, to the contrary, you have a recursive function. Sign up to join this community. The best answers are voted up and rise to the top. Home Questions Tags Users Unanswered. Ask Question. Asked 3 years, 6 months ago.
Active 3 years, 6 months ago.
The dark mode beta is finally here. Change your preferences any time. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information.
Let's say you wanted to implement a breadth-first search of a binary tree recursively. How would you go about it?
Breadth-first traversal traditionally uses a queue, not a stack. The nature of a queue and a stack are pretty much opposite, so trying to use the call stack which is a stack, hence the name as the auxiliary storage a queue is pretty much doomed to failure, unless you're doing something stupidly ridiculous with the call stack that you shouldn't be. On the same token, the nature of any non-tail recursion you try to implement is essentially adding a stack to the algorithm.
This makes it no longer breadth first search on a binary tree, and thus the run-time and whatnot for traditional BFS no longer completely apply. Of course, you can always trivially turn any loop into a recursive call, but that's not any sort of meaningful recursion. However, there are ways, as demonstrated by others, to implement something that follows the semantics of BFS at some cost. If the cost of comparison is expensive but node traversal is cheap, then as Simon Buchan did, you can simply run an iterative depth-first search, only processing the leaves.
This would mean no growing queue stored in the heap, just a local depth variable, and stacks being built up over and over on the call stack as the tree is traversed over and over again. And as Patrick noted, a binary tree backed by an array is typically stored in breadth-first traversal order anyway, so a breadth-first search on that would be trivial, also without needing an auxiliary queue.
If you use an array to back the binary tree, you can determine the next node algebraically. Here's pseudocode for a very naive implementation of breadth first search on an array backed binary search tree. This assumes a fixed size array and therefore a fixed depth tree.
It will look at parentless nodes, and could create an unmanageably large stack. I couldn't find a way to do it completely recursive without any auxiliary data-structure.
Breadth First Search or BFS for a Graph
But if the queue Q is passed by reference, then you can have the following silly tail recursive function:. The following method used a DFS algorithm to get all nodes in a particular depth - which is same as doing BFS for that level. If you find out depth of the tree and do this for all levels, the results will be same as a BFS. I found a very beautiful recursive even functional Breadth-First traversal related algorithm.
Not my idea, but i think it should be mentioned in this topic. Here's a Scala 2. I've sacrificed tail-call optimization for brevity, but the TCOd version is very similar. See also snv 's post. The following seems pretty natural to me, using Haskell.The only catch here is, unlike trees, graphs may contain cycles, so we may come to the same node again.
To avoid processing a node more than once, we use a boolean visited array. For simplicity, it is assumed that all vertices are reachable from the starting vertex. For example, in the following graph, we start traversal from vertex 2.
When we come to vertex 0, we look for all adjacent vertices of it. A Breadth First Traversal of the following graph is 2, 0, 3, 1. The implementation uses adjacency list representation of graphs.
Illustration :. Note that the above code traverses only the vertices reachable from a given source vertex. All the vertices may not be reachable from a given vertex example Disconnected graph.
To print all the vertices, we can modify the BFS function to do traversal starting from all nodes one by one Like the DFS modified version. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Writing code in comment? Please use ide. BFS int s traverses vertices.
Graph::Graph int V. If a adjacent has not been visited. Graph g 4. BFS 2. Graph int v. Python3 Program to print BFS traversal. BFS int s. This class represents a directed graph. Function to print a BFS of graph. Mark all the vertices as not visited. Create a queue for BFS. Mark the source node as. Dequeue a vertex from. Get all adjacent vertices of the. If a adjacent. BFS 2. This code is contributed by Neelam Yadav. Load Comments. Python3 Program to print BFS traversal from a given source vertex.
BFS int s traverses vertices reachable from s.I know how to implement dfs using recursion but i couldn't implement bfs using recursion Can some one help me with the recursion code?
Thanks in advance. BFS can't be done by recursion as BFS goes level by levelwhich can't be done by a recursive function which goes as deep as it can then go back when it ends a path and so on. Not to be facetious, but you can easily implement BFS using recursion.
DFS uses a stack to maintain a frontier, and recursion uses or utilizes a stack to maintain, well, the 'call stack'. Implementing DFS using recursion simply means replacing the stack with a call stack.
Since BFS does not use a stack, there is nothing we can replace with the call stack, and thus this implementation feels a bit unnatural.
As you can see, recursion is not an integral part of the algorithm, but is just used to 'loop', really. That said, you'll get stackoverflow errors on moderately sized graphs. So just use an iterative implementation, please. How to calculate the shortest path length between two vertices using Bfs in a graph??
How to print the shortest path? Enter Register. Before contest Codeforces Round Div. Help needed. Bfs using recursion. Comments 7. Write comment? Figured out. In English In Russian. Codeforces c Copyright Mike Mirzayanov. Desktop version, switch to mobile version. User lists. M iFaFaOvO. B enq. L HiC. Countries Cities Organizations.Depth-first search DFS is an algorithm that traverses a graph in search of one or more goal nodes.
As we will discover in a few weeks, a maze is a special instance of the mathematical object known as a "graph". In the meantime, however, we will use "maze" and "graph" interchangeably. The defining characteristic of this search is that, whenever DFS visits a maze cell cit recursively searches the sub-maze whose origin is c.
This recursive behaviour can be simulated by an iterative algorithm using a stack. A cell can have three states: Unvisited. The cell has not yet been visited by DFS. Visit In Progress. The cell has been discovered, but not yet finished.
DFS traversal of a tree using recursion
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It only takes a minute to sign up. I'm somewhat new to the wonderful world of Python, outside of simple codecademy-like challenges online. This function was part of a project for school. It's tested and works, but I'm looking for some feedback.Breadth First Search grid shortest path - Graph Theory
Did I over-think it? I don't think recursion was necessary, but I was in that mindset from the previous portion of the assignment which was a similar function for DFS. Below is my code, the input format a dictionary and a visual representation of the tree that I used to test it:.
You're off to a good start. In cases like this, most of my comments come down to best-practices for coding standards. I break down a few areas, starting from nitpicks to almost-bugs:. In the python world it is worth familiarizing yourself with PEP8which sets suggested standards for code formatting across the python world.
Yours looks pretty close to most of the standards, but one thing you are missing is your indentation. Also, a space between parameters is recommended. Believe it or not, these things matter: in almost all cases, code is read more than it is written. As a result, it is important for long-term maintenance to write code that is consistent and easy-to-read.
Doc strings are the preferred way of commenting your code. Comments themselves should be used sparingly you don't have any, which for a function of this size is finebut doc strings should be used pretty much everywhere. These are a formatted block of text, inside a comment, that comes right before your function definition also classes and modules.
It describes the parameters, what the function does, and what it returns. See here:. Instead of putting all of your code inside an indented block, this is one of many cases where a guard clause will make your code more readable.
At the top, put conditions on cases where you don't need to do any processing, and exit early. Recursion here is perfectly fine. You didn't overthink it or overdo it. It actually fits perfectly in this case, and recursion is usually a harder concept to grasp, so anything that helps you practice it without making the code a tangled mess is a good choice.
Your default value for the level parameter only works for your given example. As a result, it is best to kill it. Just make it a required positional parameter. Your code assumes that it is passed in a valid tree.