图的邻接矩阵表示及深度、广度遍历

#include #include #define EdgeNum 50 #define VerticeNum 10 using namespace std; int visit[VerticeNum]={0}; int c=0; struct Node { char verlist[VerticeNum];//顶点列表 int edgelist[VerticeNum][VerticeNum];//邻接矩阵 int n;//当前顶点数 int e;//当前边数 }; typedef struct Node Node; typedef struct Node *PNode; typedef PNode Graph; struct node { int element; struct node *front; struct node *rear; struct node *next; }; typedef struct node *pnode; typedef pnode QUEUE; void makeNULL(QUEUE Q)//初始化 { Q->front=new (struct node); Q->rear=new (struct node); Q->rear=Q->front; Q->front->next=NULL; } int isEmpty(QUEUE Q)//判断是否为空 { if(Q->front==Q->rear) return 1; else return 0; } int deleteQUEUE(QUEUE Q)//删除队列元素并返回 { QUEUE tmp; if(isEmpty(Q)==1) { return 0; } else { tmp=Q->front->next; Q->front->next=tmp->next; if(Q->front->next==NULL) { Q->rear=Q->front; } return tmp->element; free(tmp); } } void EnQUEUE(QUEUE Q,int x)//将元素插入队列 { QUEUE q1; q1=new (struct node); q1->element=x; q1->next=NULL; if(Q->front->next==NULL) { Q->front->next=q1; } Q->rear->next=q1; Q->rear=q1; } int FRONT(QUEUE Q)//返回队列的头元素 { QUEUE q1; q1=Q->front->next; return q1->element; } Graph createGraph(Graph G,int flag)//建立有、无向图 { int i,j,k; cout<<“输入要建立的无向图的顶点个数,边的条数:”; cin>>G->n>>G->e; cout<<“输入顶点:”; for(i=0;in;i++) { cin>>G->verlist[i]; } for(i=0;in;i++) for(j=0;jn;j++) { G->edgelist[i][j]=0;//初始化图的邻接矩阵 } cout<<“输入邻接矩阵的行,列:”; for(k=0;ke;k++) { cin>>i>>j; G->edgelist[i][j]=1; if(flag==1) G->edgelist[j][i]=1; } return G; } void Output(Graph G)//输出建立的图 { int i,j; for(i=0;in;i++) for(j=0;jn;j++) { if(j==0) cout<<endl; cout<edgelist[i][j]<<” “; } } void BFS(Graph G,int i)//广度优先 { int j=0; int bfn[VerticeNum]={0}; QUEUE Q; Q = new (struct node); makeNULL(Q); cout<verlist[i]<<” “; visit[i]=1; EnQUEUE(Q,i); while(!isEmpty(Q)) { i=deleteQUEUE(Q); for(j=0;jn;j++) { if(G->edgelist[i][j]==1 && visit[j]==0) { cout<verlist[j]<<” “; visit[j]=1; EnQUEUE(Q,j); } } } } void DFS(Graph G,int i)//递归深度搜索 { int j=0; int dfn[VerticeNum]={0}; cout<verlist[i]<<” “; visit[i]=1; dfn[i]=c; c++; for(j=0;jn;j++) { if((G->edgelist[i][j]!=0) && visit[j]==0) DFS(G,j); } } int main() { Graph G = new (Node); int flag; int sw=0; cout<<“输1建立无向图,输0建立有向图:”; cin>>flag; G=createGraph(G,flag); Output(G); cout<<“1.深度搜索 2.广度搜索”<>sw; switch(sw) { case 1: DFS(G,0); break; case 2: BFS(G,0); break; } return 0; }

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