使用邻接矩阵和邻接表存储结构存储图,并分别对这两种存储结构存储的图进行DFS和B完整代码
时间: 2023-08-10 18:04:54 浏览: 95
邻接矩阵存储结构下 DFS 的完整代码:
```c++
#include<iostream>
#include<cstring>
using namespace std;
const int N = 1e5 + 10;
int n, m;
int g[N][N];
bool st[N];
void dfs(int u) {
cout << u << " ";
st[u] = true;
for (int i = 1; i <= n; i++) {
if (g[u][i] && !st[i]) {
dfs(i);
}
}
}
int main() {
cin >> n >> m;
while (m--) {
int a, b;
cin >> a >> b;
g[a][b] = g[b][a] = 1;
}
for (int i = 1; i <= n; i++) {
if (!st[i]) {
dfs(i);
}
}
return 0;
}
```
邻接表存储结构下 DFS 的完整代码:
```c++
#include<iostream>
#include<cstring>
#include<vector>
using namespace std;
const int N = 1e5 + 10;
int n, m;
vector<int> g[N];
bool st[N];
void dfs(int u) {
cout << u << " ";
st[u] = true;
for (int i = 0; i < g[u].size(); i++) {
int v = g[u][i];
if (!st[v]) {
dfs(v);
}
}
}
int main() {
cin >> n >> m;
while (m--) {
int a, b;
cin >> a >> b;
g[a].push_back(b);
g[b].push_back(a);
}
for (int i = 1; i <= n; i++) {
if (!st[i]) {
dfs(i);
}
}
return 0;
}
```
邻接矩阵存储结构下 BFS 的完整代码:
```c++
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int N = 1e5 + 10;
int n, m;
int g[N][N];
bool st[N];
void bfs(int start) {
queue<int> q;
q.push(start);
st[start] = true;
while (q.size()) {
int t = q.front();
q.pop();
cout << t << " ";
for (int i = 1; i <= n; i++) {
if (g[t][i] && !st[i]) {
q.push(i);
st[i] = true;
}
}
}
}
int main() {
cin >> n >> m;
while (m--) {
int a, b;
cin >> a >> b;
g[a][b] = g[b][a] = 1;
}
for (int i = 1; i <= n; i++) {
if (!st[i]) {
bfs(i);
}
}
return 0;
}
```
邻接表存储结构下 BFS 的完整代码:
```c++
#include<iostream>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;
const int N = 1e5 + 10;
int n, m;
vector<int> g[N];
bool st[N];
void bfs(int start) {
queue<int> q;
q.push(start);
st[start] = true;
while (q.size()) {
int t = q.front();
q.pop();
cout << t << " ";
for (int i = 0; i < g[t].size(); i++) {
int v = g[t][i];
if (!st[v]) {
q.push(v);
st[v] = true;
}
}
}
}
int main() {
cin >> n >> m;
while (m--) {
int a, b;
cin >> a >> b;
g[a].push_back(b);
g[b].push_back(a);
}
for (int i = 1; i <= n; i++) {
if (!st[i]) {
bfs(i);
}
}
return 0;
}
```
阅读全文
相关推荐

















