广度优先搜索BFS——图邻接矩阵表示

这个是基于邻接矩阵的BFS图算法。

/*
图邻接矩阵表示DFS
input:
1
7
A 0 0 0 0 1 0 0
B 0 0 1 1 0 0 0
C 0 1 0 1 0 0 0
D 0 1 0 0 1 1 0
E 1 0 0 1 0 0 1
F 0 0 0 1 0 0 0
G 0 0 0 0 1 0 0
output:
A E D G B F C
*/
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
struct Graph{
    //图邻接矩阵表示
    char data;
    bool *adjacency;
};
void Create(Graph G[],int n){
    //创建图邻接矩阵表示
    int i,j;
    for(i=1; i<=n; i++){
        cin>>G[i].data;
        G[i].adjacency = new bool[n];
        for(j=1; j<=n; j++)cin>>G[i].adjacency[j];
    }
}
void BFS(Graph G[],int vex,int n,bool visited[]){
    //图邻接矩阵BFS
    queue<int> q;
    int temp,i;
    q.push(vex);
    while(!q.empty()){
        temp = q.front();
        q.pop();
        if(!visited[temp]){
            visited[temp] = true;
            cout<<G[temp].data<<' ';
            for(i=1; i<=n; i++){
                if(!visited[i] && G[temp].adjacency[i])
                q.push(i);
            }
        }
    }
}
int main(){
    Graph *G;
    bool *visited;
    int t,n;
    cin>>t;
    while(t--){
        cin>>n;
        G = new Graph[n];
        visited = new bool[n];
        memset(visited,0,sizeof(visited));
        Create(G,n);
        BFS(G,1,n,visited);
        cout<<endl;
    }
    return 0;
}


  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值