#include #include #include #include #include #include using namespace std; unordered_map> G; // the adjacency list unordered_map visited; unordered_map parent; void Tokenize(string line, vector & tokens, string delimiters){ string token = ""; string OneCharString = " "; for (int i=0; i tokens; Tokenize(line, tokens, " \t"); if (tokens.size()!=2) continue; G[tokens[0]].push_back(tokens[1]); G[tokens[1]].push_back(tokens[0]); } inf.close(); } // assuming that nodes have unique string identifiers void DFS(string v, vector& ret){ visited[v] = true; ret.push_back(v); for (int i=0; i< G[v].size(); i++){ if (!visited[G[v][i]]){ parent[G[v][i]] = v; DFS(G[v][i], ret); } } } vector BFS(string v){ vector ret; queue q; q.push(v); visited[v] = true; while (!q.empty()){ string u = q.front(); q.pop(); ret.push_back(u); for (int i=0; i< G[u].size(); i++){ if (visited[G[u][i]]) continue; q.push(G[u][i]); visited[G[u][i]] = true; } } return ret; } vector get_reverse_path(string u, string v){ vector ret; ret.push_back(v); while (v!=u){ v = parent[v]; ret.push_back(v); } return ret; } int main(int argc, char** argv){ if (argc!=4){ cout <<"Parameters: graph u v" << endl; return 1; } readGreaph(argv[1]); string u = argv[2]; string v = argv[3]; cout << "Path found by DFS:" << endl; vector output; DFS(u, output); vector path = get_reverse_path(u, v); for (int i=path.size()-1; i>=0; i--) cout << path[i] << "\t"; cout << endl; visited.clear(); parent.clear(); cout << "Path found by BFS:" << endl; output = BFS(argv[2]); path = get_reverse_path(u, v); for (int i=path.size()-1; i>=0; i--) cout << path[i] << "\t"; cout << endl; cout << "All done!\n"; return 0; }