[算法笔记]图的遍历

一:深度优先遍历(DFS)

每次沿着路径到不能再前进的时候才退回到最近的岔道口
每一次DFS过程可以遍历一个连通分量,遍历所有联通分量即遍历图

//邻接矩阵存储

const int maxv=10000;
const int INF=1000000000;
bool vis[maxv]={false};
int n,G[maxv][maxv];
void DFS(int u,int depth){
    vis[u]=true;
    for(int v=0;v<maxv;v++){
        if(vis[i]==false&&G[u][v]!=INF){
            DFS(v,depth+1);
        }
    }
}
void DFSTrave(){
    for(int u=0;u<maxv;u++){
        if(vis[u]==false){
            DFS(u,1);
        }
    }
}

//邻接表存储

vector<int> Adj[maxv];
int n;
void DFS(int u,int depth){
    vis[u]=true;
    for(int i=0;i<Adj[u].size();i++){
        int v=Adj[u][i];
        if(vis[v]==false){
            DFS(v,depth+1);
        }
    }
}
void DFSTrave(){
    for(int u=0;u<maxv;u++){
        if(vis[u]==false){
            DFS(u,1);
        }
    }
}

二:广度优先遍历(BFS)

使用一个队列,通过反复取出队首顶点,将该顶点可到达的未曾加入过队列的顶点全部入队,直到队列为空时遍历结束
同DFS,遍历所有联通分量,即遍历完图

//邻接矩阵存储

int n,G[maxv][maxv];
bool inq[maxv]={false};//标记有没有进过队列
void BFS(int u){
    queue<int> q;
    q.push(u);
    inq[u]=true;
    while(!q.empty()){
        int u=q.front();
        q.pop();
        for(int v=0;v<n;v++){
            if(inq[v]==false&&G[u][v]!=INF){
                q.push(v);
                inq[v]=true;
            }
        }
    }
}

//邻接表存储

vector(int) Adj[maxv];
int n;
bool inq[maxv]={false};
void BFS(int u){
    queue<int> q;
    q.push(u);
    inq[u]=true;
    while(!q.empty()){
        int u=q.fornt();
        q.pop();
        for(int i=0;i<Adj[u].size();i++){
            int v=Adj[u][i];
            if(inq[v]!=false){
                q.push(v);
                inq[v]==ture;
            }
            
        }
    }
}

void BFSTrave(){
    for(int u=0;u<n;u++){
        if(inq[u]==false){
            BFS(u);
        }
    }
}

//如果需要配合层号的传递关系,则在结构体中定义层号,在队列循环中处理层数

struct Node{
    int v;
    int layer;
}
vector<Node> Adj[maxv];
void BFS(int s){
    queue<Node> q;
    Node start;
    start.v=s;
    start.layer=0;
    q.push(start);
    inq[start.v]=true;
    while(!q.empty()){
        Node topNode=q.front();
        q.pop();
        int u=topNode.v;
        for(int i=0;i<Adj[u].size();i++){
            Node next=Adj[u][i];
            next.layer=topNode.layer+1;
            if(inq[next.v]==false){
                q.push(next);
                inq[next.v]=true;
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值