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 ();}}
}