自定义有向图,将其储存为邻接矩阵,分别采用bfs,dfs算法计算任意两顶点是否可达,形成可达矩阵,利用warshall算法计算可达矩阵
时间: 2024-04-07 14:30:03 浏览: 67
好的,我将根据您的要求给出一个使用邻接矩阵表示有向图,并使用BFS和DFS算法计算任意两个顶点之间的可达性,并使用Warshall算法计算可达矩阵的示例代码。
```cpp
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
// 广度优先搜索(BFS)
void bfs(vector<vector<int>>& graph, int start, vector<vector<bool>>& reachable) {
int numNodes = graph.size();
vector<bool> visited(numNodes, false); // 记录节点是否已访问
queue<int> q; // 存储待访问的节点
visited[start] = true;
q.push(start);
while (!q.empty()) {
int current = q.front();
q.pop();
for (int neighbor = 0; neighbor < numNodes; neighbor++) {
if (graph[current][neighbor] && !visited[neighbor]) {
visited[neighbor] = true;
q.push(neighbor);
reachable[start][neighbor] = true;
}
}
}
}
// 深度优先搜索(DFS)
void dfs(vector<vector<int>>& graph, int start, vector<vector<bool>>& reachable) {
int numNodes = graph.size();
vector<bool> visited(numNodes, false); // 记录节点是否已访问
visited[start] = true;
for (int neighbor = 0; neighbor < numNodes; neighbor++) {
if (graph[start][neighbor] && !visited[neighbor]) {
reachable[start][neighbor] = true;
dfs(graph, neighbor, reachable);
}
}
}
// Warshall算法计算可达矩阵
void warshall(vector<vector<bool>>& reachable) {
int numNodes = reachable.size();
for (int k = 0; k < numNodes; k++) {
for (int i = 0; i < numNodes; i++) {
for (int j = 0; j < numNodes; j++) {
reachable[i][j] = reachable[i][j] || (reachable[i][k] && reachable[k][j]);
}
}
}
}
int main() {
int numNodes, numEdges;
cout << "请输入节点数和边数:";
cin >> numNodes >> numEdges;
vector<vector<int>> graph(numNodes, vector<int>(numNodes, 0)); // 图的邻接矩阵表示
vector<vector<bool>> reachable(numNodes, vector<bool>(numNodes, false)); // 可达矩阵
cout << "请输入每条边的连接关系:\n";
for (int i = 0; i < numEdges; i++) {
int u, v;
cin >> u >> v;
graph[u][v] = 1; // 有向边
}
// 使用BFS计算可达矩阵
for (int i = 0; i < numNodes; i++) {
bfs(graph, i, reachable);
}
cout << "通过BFS计算的可达矩阵:\n";
for (int i = 0; i < numNodes; i++) {
for (int j = 0; j < numNodes; j++) {
cout << reachable[i][j] << " ";
}
cout << endl;
}
// 使用DFS计算可达矩阵
reachable.assign(numNodes, vector<bool>(numNodes, false)); // 重置可达矩阵
for (int i = 0; i < numNodes; i++) {
dfs(graph, i, reachable);
}
cout << "通过DFS计算的可达矩阵:\n";
for (int i = 0; i < numNodes; i++) {
for (int j = 0; j < numNodes; j++) {
cout << reachable[i][j] << " ";
}
cout << endl;
}
// 使用Warshall算法计算可达矩阵
warshall(reachable);
cout << "通过Warshall算法计算的可达矩阵:\n";
for (int i = 0; i < numNodes; i++) {
for (int j = 0; j < numNodes; j++) {
cout << reachable[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
在此代码示例中,我们首先输入节点数和边数,然后逐一输入每条边的连接关系。接下来,我们使用BFS和DFS算法分别计算可达矩阵,并使用Warshall算法对可达矩阵进行计算。最后,我们输出通过BFS、DFS和Warshall算法计算得到的可达矩阵。
请注意,此示例假设节点编号从0开始,并且输入的图是有向图。您可以根据需要进行修改和扩展。
阅读全文