Solve for the fastest parcel shipping path built by the city. The cost between each two citys are the same. The city defined in two capital letters.
BFS. Using bfs to solve the shortest path problem.
#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <map>
using namespace std;
map <string, vector<string> > adjacency_list;
int bfs(string s, string t)
{
map <string, int> visit;
visit[s] = 1;
map <string, string> parent;
parent[s] = s;
queue<string> Q;
Q.push(s);
string Now, New;
while (!Q.empty()) {
Now = Q.front(); Q.pop();
for (int i = adjacency_list[Now].size()-1; i >= 0; -- i) {
New = adjacency_list[Now][i];
if (!visit[New]) {
visit[New] = 1;
parent[New] = Now;
Q.push(New);
if (New == t) {
stack <string> S;
while (New != s) {
S.push(New);
New = parent[New];
}
New = s;
while (!S.empty()) {
cout << New << " ";
New = S.top();
cout << New << endl;
S.pop();
}
return 1;
}
}
}
}
std::cout << "No route" << std::endl;
return 0;
}
int main()
{
int n, cases = 0;
string s, t;
while (cin >> n) {
adjacency_list.clear();
for (int i = 0; i < n; ++ i) {
cin >> s >> t;
adjacency_list[s].push_back(t);
adjacency_list[t].push_back(s);
}
cin >> s >> t;
if (cases ++)
cout << endl;
bfs(s, t);
}
return 0;
}