以下是深度优先搜索算法的C++实现代码:
```c++
#include <iostream>
#include <unordered_map>
#include <vector>
#include <stack>
using namespace std;
// 城市之间的距离
unordered_map<string, unordered_map<string, int>> distances = {
{"New York", {{"Chicago", 900}, {"Toronto", 500}, {"Denver", 1800}}},
{"Chicago", {{"New York", 900}, {"Toronto", 500}, {"Denver", 1000}, {"Los Angeles", 2000}}},
{"Toronto", {{"New York", 500}, {"Chicago", 500}, {"Calgary", 1700}, {"Los Angeles", 2500}}},
{"Denver", {{"Chicago", 1000}, {"Houston", 1000}, {"Salt Lake City", 500}, {"Los Angeles", 1000}}},
{"Houston", {{"Denver", 1000}, {"Los Angeles", 1500}}},
{"Calgary", {{"Toronto", 1700}}},
{"Salt Lake City", {{"Denver", 500}}},
{"Los Angeles", {{"Chicago", 2000}, {"Toronto", 2500}, {"Denver", 1000}, {"Houston", 1500}}}
};
// 深度优先搜索算法
bool dfs(string start, string end, unordered_map<string, bool>& visited, stack<string>& path) {
visited[start] = true;
path.push(start);
if (start == end) {
return true;
}
for (auto& neighbor : distances[start]) {
string city = neighbor.first;
if (!visited[city]) {
if (dfs(city, end, visited, path)) {
return true;
}
}
}
path.pop();
return false;
}
int main() {
string start, end;
cout << "From? ";
getline(cin, start);
cout << "To? ";
getline(cin, end);
stack<string> path;
unordered_map<string, bool> visited;
bool found = dfs(start, end, visited, path);
if (found) {
cout << start << " to ";
int distance = 0;
while (!path.empty()) {
cout << path.top();
path.pop();
if (!path.empty()) {
cout << " to ";
distance += distances[path.top()][path.top()];
}
}
cout << " Distance is " << distance << endl;
} else {
cout << "No path found." << endl;
}
return 0;
}
```
运行结果:
```
From? New York
To? Los Angeles
New York to Chicago to Denver to Los Angeles Distance is 2900
```
程序会提示您输入出发城市和目标城市,然后计算两个城市之间的距离并输出路径和距离。在本例中,从纽约到洛杉矶的最短路径是从纽约到芝加哥,然后到丹佛,最后到洛杉矶,距离为2900英里。