用c++实现输入邻接矩阵构建图并统计边的条数,在广度搜索的基础上搜索节点路径
时间: 2024-05-01 19:22:12 浏览: 66
以下是用 C++ 实现输入邻接矩阵构建图并统计边的条数,并在广度搜索的基础上搜索节点路径的代码:
```c++
#include <iostream>
#include <queue>
using namespace std;
const int MAXN = 100;
bool visited[MAXN];
int edges[MAXN][MAXN];
int n, m;
void bfs(int start, int end) {
queue<int> q;
q.push(start);
visited[start] = true;
while (!q.empty()) {
int u = q.front();
q.pop();
for (int v = 0; v < n; v++) {
if (!visited[v] && edges[u][v] != 0) {
visited[v] = true;
q.push(v);
}
}
}
}
int main() {
cin >> n >> m;
int u, v;
for (int i = 0; i < m; i++) {
cin >> u >> v;
edges[u][v] = 1;
edges[v][u] = 1; // 无向图,需要反向也赋值为 1
}
int cnt = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (edges[i][j] == 1) {
cnt++;
}
}
}
cout << "The graph has " << cnt << " edges." << endl;
int start, end;
cout << "Enter the start node and the end node to search the path: ";
cin >> start >> end;
bfs(start, end);
if (visited[end]) {
cout << "There is a path from " << start << " to " << end << endl;
} else {
cout << "There is no path from " << start << " to " << end << endl;
}
return 0;
}
```
使用邻接矩阵来存储图,输入格式为 `n m` 表示有 `n` 个节点和 `m` 条边,接下来 `m` 行每行输入一条边的两端节点编号。首先统计边的条数,然后输入需要搜索的起点和终点,在广度搜索的过程中标记已访问的节点,最后判断是否存在从起点到终点的路径。
阅读全文