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..
# | User | Rating |
---|---|---|
1 | tourist | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 160 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | Dominater069 | 154 |
8 | awoo | 154 |
10 | luogu_official | 150 |
Name |
---|
First, think about the data structure of BFS and DFS.
BFS can't be done by recursion as BFS goes level by level , which 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. What you probably mean is "BFS and recursion cannot be combined as naturally as DFS and recursion can be combined". 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.
That said, BFS with recursion would sort of look like this:
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.
you can do the dfs iterative, like the bfs using a stack, but implement a bfs using recursion it is not necessary, because you are increasing the complexity of the method.
And speaking like crazy people, maybe are something like this:
How to calculate the shortest path length between two vertices using Bfs in a graph?? How to print the shortest path?
You can find the code here which does that you want: http://e-maxx.ru/algo/bfs keeps nodes ancestor nodes in p and then reconstructs the whole path.