1 solutions

  • 0
    @ 2025-3-3 16:24:07

    C++ :

    #include<iostream>
    #include<cstring>
    #include<queue>
    #include<cstdio>
    using namespace std;
    bool a[110][110];
    bool flag[110];
    int n,e;
    void init();
    void bfs(int x);
    int main()
    {
    	//freopen("bfs5.in","r",stdin);
    	//freopen("bfs5.out","w",stdout);
    	init();
    	bfs(1);
    	return 0;
    }
    void init()
    {
    	cin>>n>>e;
    	memset(flag,0,sizeof(flag));
    	memset(a,0,sizeof(a));
    	int x,y;
    	for(int i=1;i<=e;++i)
    	{
    		cin>>x>>y;
    		a[x][y]=1;//无向图处理双向 
    		a[y][x]=1;
    	}
    }
    void bfs(int x)
    {
    	queue<int> q;
    	cout<<x<<' ';
    	flag[x]=1;//把遍历点设为已访问 
    	q.push(x);//把当前点进队 
    	while(!q.empty())//当队列非空	
    	{
    		for(int i=1;i<=n;i++)
    		{
    			if(!flag[i]&&a[q.front()][i])//遍历队首元素的相邻点 
    			{
    				cout<<i<<' ';//如果连通且没访问过进队 
    				flag[i]=1;//一定要记得设访问标记,否会是死循环 
    				q.push(i);
    			}
    		}
    		q.pop();
    	}
    }
    
    
    • 1

    Information

    ID
    9995
    Time
    1000ms
    Memory
    128MiB
    Difficulty
    (None)
    Tags
    # Submissions
    0
    Accepted
    0
    Uploaded By