用数组模拟邻接表(dfs+bfs)//链式前向星

测试数据

10 9
1 2
2 4
2 5
4 8
5 9
1 3
3 6
3 7
7 10

这个是测试数据的图

//本文借鉴了闫老师的文章https://www.acwing.com/blog/content/405/
#include<bits/stdc++.h>
using namespace std;
const int N=1010;
int e[N],ne[N],h[N],num;
bool vis[N];//dfs标记
 bool flag[N];//bfs
int n,m;
void add(int a,int b)
{
	e[num]=b;
	ne[num]=h[a];
	h[a]=num++;
	
}
void dfs(int u)
{
	vis[u]=true;
	for(int i=h[u];i!=-1;i=ne[i])
	{
		int j=e[i];
		if(vis[j]==false) 
		{
			cout<<j<<" ";//输出遍历顶点的顺序 
			dfs(j);	
		}
	}

}
void bfs(int u)
{
   queue<int>q;
  
   q.push(u);
   flag[u]=true;//
    
   while(q.size()>0)
   {
   	int t=q.front();
   	cout<<t<<" ";
   	q.pop();
   	for(int i=h[t];i!=-1;i=ne[i])
   	{
   		int j=e[i];
   		if(flag[j]==false)
   		{
   			flag[j]=true;
   			//cout<<j<<" ";
   			q.push(j);
   		
		}
	}
   }
 } 
int main()
{
	
	cin>>n>>m;
	memset(h,-1,sizeof(h));
	for(int i=0;i<m;i++)
	{
		int a,b;
		cin>>a>>b;
		add(a,b);
		add(b,a);
	}
	  dfs(2);//非常正确
	  cout<<endl;
	 bfs(1);//正确 

}
发布了78 篇原创文章 · 获赞 30 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_42333573/article/details/99669772