题解 | 小红走迷宫

小红走迷宫

https://www.nowcoder.com/practice/a9294fa256ac4b63ab23ce15ec167a55

#include <bits/stdc++.h>
#define int long long
using namespace std;
#define endl '\n'
void work() 
{
    int n , m , x ; cin >> n >> m >> x ;
    vector<bool>vis(n + 1 , false);
    for(int i = 1 ; i <= x ; i++)
    {
        int y ; cin >> y ;
        vis[y] = true ; 
    }
    vector<vector<int>>mp(n + 1);
    for(int i = 1 ; i <= m ; i++)
    {
        int u , v ; cin >> u >> v ; 
        mp[u].push_back(v);
        mp[v].push_back(u);
    }
    vector<int>ans ; 
    queue<int>q ; 
    q.push(1);
    vis[1] = true ; 
    while(q.size())
    {
        int x = q.front() ;
        ans.push_back(x);
        q.pop() ; 
        for(int i = 0 ; i < mp[x].size() ; i++)
        {
            int jk = mp[x][i] ; 
            if(!vis[jk])
            {
                vis[jk] = true ; 
                q.push(jk);
            }
        }
    }
    sort(ans.begin() , ans.end());
    for(int i = 0 ; i < ans.size() ; i++)
    {
        cout << ans[i] << " " ; 
    }
}
signed main() 
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int t = 1;
    while (t--) 
    {
        work();
    }
    return 0;
}

本人并不会并查集,所以水一篇使用了bfs的题解,本题目不能使用dfs,否则会因为深度过大而导致栈溢出

全部评论

相关推荐

03-12 15:35
嘉应学院 Python
快说谢谢牛牛精灵:说不定就是下一个寒武纪!
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务