图的广度深度遍历(邻接矩阵)

#include <iostream>
#include <queue>
#include <algorithm>
#include <stack>
using namespace std;
int a[5][5]={{0,1,0,1,0},{1,0,1,0,1},{0,1,0,1,1},{1,0,1,0,0},{1,0,1,0,0}};
template<int n>
void bfs(int i){
    queue<int> q;
    bool flag[n];
    memset(flag,false,n);
    q.push(i);
    flag[i]=true;
    while(!q.empty()){
        int k = q.front();
        q.pop();
        cout<<k<<" ";
        for(int j=0;j<n;j++){
            if(a[k][j]&&!flag[j]){
                q.push(j);
                flag[j]=true;
            }
        }
    }


}
template<int n>
void dfs(int i){
    stack<int> s;
    bool flag[n];
    memset(flag,false,n);
    s.push(i);
    flag[i]=true;
    while(!s.empty()){
        int k= s.top();
        s.pop();
        cout<<k<<" ";
        for(int j=0;j<n;j++){
            if(a[k][j]&&!flag[j]){
                s.push(j);
                flag[j]=true;
            }
        }
    }
}
int main(){
    bfs<5>(0);
    cout<<endl;
    dfs<5>(0);
}

 

    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/iteye_19330/article/details/82369299
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞