Graph traversal, non-recursive version, depth-first traversal

Source: Internet
Author: User

Undirectedgraphnode is the graph node, the label stores the node data, visited indicates whether the node has been accessed, neighbors represents the connected node.

Using stack to achieve the deep traversal of the graph, the stack is implemented by the back (), push_back (), Pop_back method of the list.

Traversal idea: The first node is pressed into Stack_node, and Stack_node.back () represents the node that is currently being accessed.

If there are contiguous nodes that have not yet been accessed, they are pressed into Stack_node, marked as accessed, and the newly pressed node as the current node continues to explore.

If there are no contiguous nodes that have not yet been accessed, the current node pops up, and the next node of Stack_node is used as the current node to continue exploring.


Perform the above two detections until stack_node all pops up, indicating that all nodes have been accessed. Traversal is complete.


struct Undirectedgraphnode {
	int label;
	bool visited = false;
	
    Vector<undirectedgraphnode *> Neighbors;
    Undirectedgraphnode (int x): label (x) {};
};


/**
 * Non-recursive version, traversing all nodes of the graph, depth-first traversal
 * *
/void Visited_non_recusive (undirectedgraphnode* node) {

	list <UndirectedGraphNode*> Stack_node;
	Stack_node.push_back (node);
	
	Print_node (node);
	Node->visited = true;
	
	undirectedgraphnode* tmp;
	undirectedgraphnode* iter_tmp;
	
	while (Stack_node.size () > 0) {
		tmp = Stack_node.back ();

		int i = 0;
		for (; i < tmp->neighbors.size (); i++) {
			
			iter_tmp = tmp->neighbors[i];
			
			if (iter_tmp->visited = = False) {
				
				Print_node (iter_tmp);
				
				Iter_tmp->visited = true;
				
				Stack_node.push_back (iter_tmp);
				break;
			}
		}
		
		if (i = = Tmp->neighbors.size ()) {
			stack_node.pop_back ();}}
}



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.