假设你有一个 Graph,G
你需要做的是找到从到的所有可能的路线。此外,您需要以正确的顺序打印所有路线。你会怎么做?发现节点并不难,它以正确的顺序打印它们并获得距离。start_node
finish_node
template <class VertexType>
void DepthFirstSearch(Graph<VertexType> routes, VertexType from_vertex, VertexType to_vertex)
{
stack<VertexType> mystack;
queue<VertexType> vertexQ;
int total_weight = 0;
int found_count = 0;
/*stringstream ss;*/
bool found = false;
VertexType vertex;
VertexType item;
routes.clearMarks();
// size_t i = 0;
// size_t j = 0;
mystack.push(from_vertex); // Adding Location to stack
do
{
vertex = mystack.top(); // Get top location
mystack.pop(); // Getting rid of top location
if (vertex == to_vertex) // If location == destination, then stop;
{
found = true;
found_count++;
} else {
if (!routes.isMarked(vertex)) // If route has not been traveled to
{
routes.markVertex(vertex); // Mark place
routes.goToVertices(vertex, vertexQ); // Add adjacent positions
while (!vertexQ.empty()) // While there are still positions left to test
{
item = vertexQ.front(); // Get top position
vertexQ.pop(); // Get rid of top position from stack
if (!routes.isMarked(item)) // If top position is not marked,
mystack.push(item); // Add to-visit stack
}
}
}
} while (!mystack.empty());
if(!found)
{
std::cout << "Distance: infinity" << std::endl;
std::cout << "Rout:" << std::endl;
std::cout << "None" << std::endl;
} else {
std::cout << "Found this many times: " << found_count << std::endl;
}
}
理想情况下,如果有人输入A B
,那么输出示例将是:
distance: 100
A to C, 50
C to D, 40
D to B, 10
distance: 10
A to B, 10
请注意,两者C
都有D
它们可以去的其他节点,但是即使深度优先算法会探索它们,它们的距离也不会被考虑在内。这是一个单向图,输入来自文本文件。