当前位置:网站首页>DFS and BFS concepts of trees and graphs

DFS and BFS concepts of trees and graphs

2022-07-05 03:56:00 Cherish forever

1. Depth first traversal enters the recursive call itself every time you search
2. Width first traversal is not recursive, that is, search the next node that the current node can reach until the node is searched

Use Adjacency list

Traverse : Each point will be traversed only once
1. Depth-first traversal .

Search as deep as possible , Go back when you hit the bottom , Until you search all the points .

2. Breadth first traversal .

Search widely from the root node , Search all the points on the first floor every time .


void add(int a,int b) {
    e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
 
int dfs(int x) {
    st[x]=true;
    int size=0,sum=1;
    for(int i=h[x]; i!=-1; i=ne[i]) {
        int j=e[i];
        if(st[j]) continue;
        int s=dfs(j);
        size=max(size,s);
        sum+=s;
    }
    size=max(size,n-sum);
    ans=min(size,ans);
    return sum;
}

原网站

版权声明
本文为[Cherish forever]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140717579929.html