[One algorithm] graph DFS non-recursive implementation

Source: Internet
Author: User

In the way of graph traversal, DFS and BFS are two main ways of traversal. DFS is primarily implemented using recursive thinking, and BFS mainly uses queues to hold the nodes below. One advantage of BFS is not the non-recursive form, so the likelihood of stack overflow is very small, contrary to DFS in this respect is relatively large. Therefore, how to change DFS to non-recursive form is significant.

How do I turn Dfs into a non-recursive form?

In fact, with a large hat in front of it, it is not very difficult for DFS to implement a non-recursive implementation.

The node we are going to access is therefore put into a stack, and the node is marked for access, and if the node has a child, it is considered that the child has been visited in the case of a sub-RU stack.

After the next step from the stack to pop a node, first of all to determine whether the node has been visited, if accessed, then skip, continue to judge.

[One algorithm] graph DFS non-recursive implementation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.