用数组模拟邻接表,怎么排序噢,请大佬指点
查看原帖
用数组模拟邻接表,怎么排序噢,请大佬指点
853953
ljx_gkx楼主2023/4/5 12:24
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>

using namespace std;
const int N = 1e6 + 10;
int h[N], e[N], ne[N], idx;
bool st[N];
int n, m;

void add (int a, int b)
{
    e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}

void dfs (int u)
{
    st[u] = true;   //表示该文章已经看过了!
    cout << u << " ";
    for (int i = h[u]; ~i; i = ne[i])
    {
        int v = e[i];
        if (st[v]) continue;
        dfs (v);
    }
}

void bfs (int s)
{
    memset (st, false, sizeof (st));
    queue<int> q;
    q.push(s);
    
    while (q.size())
    {
        auto t = q.front();
        q.pop();
        cout << t << " ";
        for (int i=h[t]; ~i; i = ne[i])
        {
            int v = e[i];
            if (!st[v]){
                st[v] = true;
                q.push(v);
            }
        }
    }
    
}

int main()
{
    cin >> n >> m; //n个点,m条边!
    memset(h, -1, sizeof h);
    while (m -- )
    {
        int a, b;
        cin >> a >> b;
        add(a, b);  
    }
    
    dfs (1);
    puts("");
    bfs (1);
    return 0;
}
2023/4/5 12:24
加载中...