Convert BFS code for a graph into a DFS code

半城伤御伤魂 提交于 2021-02-19 07:18:25

问题


I'm sorry if this question sounds ambiguous but I was asked this in an interview.

Write a program for BFS in a graph/tree.

I wrote the popular code using a queue.

Now he asked me to convert it to a DFS code by modifying just one line of the BFS code I had just written.

The only answer I could think of was to use a stack for DFS. Then I implemented the stack using 2 queues.

So in the end my answer was: use 1 queue for BFS. for DFS use 2 queues instead.

He did not give me any feedback . Wasn't hired :(

Is my approach fine or is there a better approach? Please help. :)


回答1:


I'll assume that your BFS answer would keep removing nodes from the queue (a FIFO data structure) until done, and for each node removed/visited, would add that node's children to the queue, because you want to visit those nodes AFTER all the ones you've found out about so far.

In DFS, you want to visit those children BEFORE any of the others you have saved so far, so you want a LIFO data structure.

Or, as @joews said: swap the queue for a stack.




回答2:


Swap the queue for a stack - there is nothing more to it.




回答3:


The interviewer maybe expecting you to use recursion.

  1. Instead of pushing the child nodes to queue, call the recursive function on them.
  2. Then proceed to traverse the siblings as presently doing.


来源:https://stackoverflow.com/questions/20788345/convert-bfs-code-for-a-graph-into-a-dfs-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!