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 98 99 100 101 102 103 104
| #include <iostream> #include <vector> #include <queue> #include <stack> #include <map>
using namespace std;
void BFS(const vector<vector<int>>& graph, const map<char, int>& vertexMap, const map<int, char>& inverseVertexMap, char start) { int n = graph.size(); std::queue<int> wait; vector<bool> visited(n, false);
wait.push(vertexMap.at(start)); visited[vertexMap.at(start)] = true;
cout << "BFS遍历结果:" << endl; while (!wait.empty()) { int current = wait.front(); cout << inverseVertexMap.at(current) << endl; wait.pop();
for (int i = 0; i < n; i++) { if (visited[i] == false && graph[current][i] != 0 && graph[current][i] != 32767) { wait.push(i); visited[i] = true; } } } }
void DFS(const vector<vector<int>>& graph, const map<char, int>& vertexMap, const map<int, char>& inverseVertexMap, char start) { int n = graph.size(); stack<int> wait; vector<bool> visited(n, false);
wait.push(vertexMap.at(start)); visited[vertexMap.at(start)] = true;
cout << "DFS遍历结果:" << endl; while (!wait.empty()) { int current = wait.top(); cout << inverseVertexMap.at(current) << endl; wait.pop();
for (int i = 0; i < n; i++) { if (visited[i] == false && graph[current][i] != 0 && graph[current][i] != 32767) { wait.push(i); visited[i] = true; } } } }
int main() { int n, m; cout << "输入顶点数与边数:\n"; cin >> n >> m;
vector<vector<int>> graph(n, vector<int>(n));
map<char, int> vertexMap; map<int, char> inverseVertexMap;
cout << "依次输入顶点字母:\n"; for (int i = 0; i < n; ++i) { char vertex; cin >> vertex; vertexMap[vertex] = i; inverseVertexMap[i] = vertex; }
cout << "输入邻接矩阵:\n"; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { cin >> graph[i][j]; } }
char start; cout << "输入 BFS 和 DFS 的起点:\n"; cin >> start; BFS(graph, vertexMap, inverseVertexMap, start); DFS(graph, vertexMap, inverseVertexMap, start);
return 0; }
|