Description:
The number of connected branches in the output graph is required.
The simplest graph traversal problem, though simple, examines the most basic traversal knowledge.
There are two common ways to traverse a graph: depth-first traversal and breadth-first traversal. They are used to access each point in the graph, but the order is different.
If the length of each side in the graph is equal (for example, 1), the process of in-depth traversal is as follows:
1. Select any point p0 as the starting point of traversal.
2. Select a node closest to p0 from the node that has never been accessed, and mark that the node has been accessed.
3. Repeat Step 1 until all nodes in the connected branch are accessed.
In terms of the image, the depth-first traversal is to access the nodes in a hierarchical order, and the nodes in each layer have the same distance as p0. First access the first layer, then access the second layer ,......
The depth-first traversal process is to access the node as deep as possible. The specific process is as follows:
1. Select any point p0 as the starting point of traversal.
2. when you access a node p1, if there is a child node under p1 that has not been traversed, we will then access a child node of p1 that has not been traversed, and mark that the subnode has been accessed,
3. If p1 does not have a child node that has not been accessed, we will return it to the parent node of p1 and execute step 1.
4. Perform steps 2nd and 3 until all nodes are accessed.
(The recursive process is really hard to describe ~~~)
As you can see, deep-first traversal is a recursive process, so it is easy to think of using the stack data structure. You can use recursion or stack for specific implementation. My habits.
The queue is required to implement the breadth-first traversal.
The code for poj2386 implementation is as follows:
Depth-first traversal and Recursion:
Depth-first traversal, stack implementation:
Breadth-first traversal: