使用邻接表来实现图的存储,编写以下算法:(1)图的创建(2)深度优先遍历(3)广度优先遍历(4)完善main()函数的编写,调用以上算法,验证算法的正确性
时间: 2024-06-13 12:05:35 浏览: 86
邻接表来实现图的存储,可以按照以下步骤编写算法:
(1) 图的创建:
```c++
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<queue>
using namespace std;
const int maxn=1005;
const int inf=0x3f3f3f3f;
int n,m;
int head[maxn],cnt;
struct Edge{
int to,next;
}edge[maxn*2];
void add(int u,int v){
edge[++cnt].to=v;
edge[cnt].next=head[u];
head[u]=cnt;
}
void create(){
cin>>n>>m;
for(int i=1;i<=m;i++){
int u,v;
cin>>u>>v;
add(u,v);
add(v,u);
}
}
```
(2) 深度优先遍历:
```c++
bool vis[maxn];
void dfs(int u){
vis[u]=true;
cout<<u<<" ";
for(int i=head[u];i;i=edge[i].next){
int v=edge[i].to;
if(!vis[v]){
dfs(v);
}
}
}
```
(3) 广度优先遍历:
```c++
void bfs(int u){
queue<int> q;
memset(vis,false,sizeof(vis));
q.push(u);
vis[u]=true;
while(!q.empty()){
int x=q.front();
q.pop();
cout<<x<<" ";
for(int i=head[x];i;i=edge[i].next){
int v=edge[i].to;
if(!vis[v]){
vis[v]=true;
q.push(v);
}
}
}
}
```
(4) 完善main()函数的编写,调用以上算法,验证算法的正确性:
```c++
int main(){
create();
dfs(1);
cout<<endl;
bfs(1);
return 0;
}
```
阅读全文
相关推荐
















