广度优先搜索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
#include
#include
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 q;
    int temp,i;
    q.push(vex);
    while(!q.empty()){
        temp = q.front();
        q.pop();
        if(!visited[temp]){
            visited[temp] = true;
            cout<>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<


你可能感兴趣的:(旧文)