No simple directed graph adjacency matrix bfs

 Above:

 

 

  Previous reference  

  The code:

#include <iostream>
#include <climits>
#include <queue>
using namespace std;

#define MAX 10

int mat[MAX][MAX];
int visited[MAX];
int n=6;

void bfs(int pos)
{
    cout<<"bfs from "<<pos<<" :"<<endl;
    queue<int> qwq;
    int r;  //记录队头
    cout<<pos<<'\t';
    qwq.push(pos);
    visited[pos]=1;
    while(!qwq.empty())
    {
        r = qwq.front();
        qwq.pop();
        for(int i=0; i<n; i++)
            if(mat[r][i]==1 && !visited[i]){
                cout<<i<<"\t";
                qwq.push(i);
                visited[i]=1;
            }
    }
}

void travelallnodes()
{
    cout<<"travel all nodes :"<<endl;
    int partnum=1;
    for(int i=0; i<n; i++){
        if(!visited[i]){
            cout<<"part "<<partnum++<<" :"<<endl;
            bfs(i);
            cout<<endl<<endl;
        }
    }
    cout<<"---travel all nodes over !"<<endl;
}

void init(){
    for(int i=0; i<n; i++)
        visited[i]=0;
    for(int i=0; i<n; i++)
        for(int j=0; j<n; j++)
            mat[i][j]=INT_MAX;
    mat[0][1]=1,mat[0][2]=1,mat[0][4] = 1 ; 
    foods [ 1 ] [ 0 ] = 1 , foods [ 1 ] [ 3 ] = 1 ; 
    food [ 2 ] [ 0 ] = 1 , food [ 2 ] [ 4 ] = 1 ; 
    food [ 3 ] [ 1 ] = 1 ; 
    food [ 4 ] [ 0 ] = 1 , food [ 4 ] [ 2 ] = 1 ;
    for ( int i = 0 ; i <n; i ++) 
        MAT [I] [I] = 0 ; 
} 

int main () 
{ 
    the init (); 
    travelallnodes (); 

    BFS ( . 1 ); // from 2 traversing 
}

 

 

 

Guess you like

Origin www.cnblogs.com/guoyujiang/p/11967310.html