1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
|
#include <iostream>
#include <stack>
#include <unordered_map>
#include <vector>
#include <string>
#include <set>
using namespace std;
unordered_map<char, vector<char>> graph = {
{'A', {'B', 'C', 'D'}},
{'B', {'A', 'F', 'E'}},
{'C', {'A', 'H', 'G'}},
{'D', {'A', 'K', 'J', 'I'}},
{'E', {'B', 'M', 'L'}},
{'F', {'B', 'P', 'N'}},
{'G', {'C', 'Q'}},
{'H', {'C', 'R'}},
{'I', {'D', 'S'}},
{'J', {'D', 'T', 'U'}},
{'K', {'D', 'V'}},
{'L', {'E', 'W'}},
{'M', {'E', 'Z', 'Y'}},
{'N', {'F'}},
{'P', {'F'}},
{'Q', {'G'}},
{'R', {'H'}},
{'S', {'I'}},
{'T', {'J'}},
{'U', {'J'}},
{'V', {'K'}},
{'W', {'L'}},
{'Y', {'M'}},
{'Z', {'M'}}
};
int dfs(char start, char goal) {
stack<vector<char>> s;
unordered_map<char, bool> visited;
set<char> vertices_visited;
s.push({ start });
visited[start] = true;
while (!s.empty()) {
vector<char> path = s.top();
s.pop();
char node = path.back();
vertices_visited.insert(node);
if (node == goal) {
cout << "Shortest path: ";
for (char vertex : path) {
cout << vertex << " -> ";
}
cout << "\b\b\b \n";
cout << "Number of vertices visited: " << vertices_visited.size() - 2 << endl;
cout << "Vertices visited: ";
for (char vertex : vertices_visited) {
if (vertex != start && vertex != goal) {
cout << vertex << " ";
}
}
cout << endl;
return path.size() - 1;
}
for (char adjacent : graph[node]) {
if (!visited[adjacent]) {
visited[adjacent] = true;
vector<char> new_path = path;
new_path.push_back(adjacent);
s.push(new_path);
}
}
}
return -1;
}
int main() {
char start = 'A';
char goal = 'W';
int nodes_expanded = dfs(start, goal);
if (nodes_expanded != -1) {
cout << "Minimum number of nodes expanded by DFS: " << nodes_expanded << endl;
}
else {
cout << "Goal state not reachable from the initial state!" << endl;
}
return 0;
}
|