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
|
#include <iostream>
#include <queue>
#include <unordered_map>
#include <vector>
#include <string>
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 bfs(char start, char goal) {
queue<vector<char>> q;
unordered_map<char, bool> visited;
q.push({ start });
visited[start] = true;
while (!q.empty()) {
vector<char> path = q.front();
q.pop();
char node = path.back();
if (node == goal) {
cout << "Shortest path: ";
for (char vertex : path) {
cout << vertex << " -> ";
}
cout << "\b\b\b \n";
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);
q.push(new_path);
}
}
}
return -1;
}
int main() {
char start = 'Z';
char goal = 'C';
int operators = bfs(start, goal);
if (operators != -1) {
cout << "Number of operators on the path found by BFS: " << operators << endl;
}
else {
cout << "Goal state not reachable from the initial state!" << endl;
}
return 0;
}
| |