[实验内容] 1、建立图的邻接矩阵-CreateMgraph; 2、进行图的深度优先遍历-DepthFirstSearch; 3、Prim算法寻找连通每个城市-MiniSpan_Prim; 4、Dijkstra算法寻找北京到西安之间的最短路径
#include<stdio.h> #include <malloc.h> #define max 20 #define INFINITY 32767 bool *visited; typedef int VertexData; typedef struct { int adj; }ArcNode; typedef struct { VertexData vexs[max]; ArcNode arcs[max][max]; int vexnum,arcnum; }AdjMatrix; void PrintDN(AdjMatrix *Net) { int i,j; printf("顶点:\n"); for(i=0;i<Net->vexnum;i++) printf("%d ",Net->vexs[i]); printf("\n"); printf("邻接矩阵:(32767代表无穷大)\n"); for(i=0;i<Net->vexnum;i++) { for(j=0;j<Net->vexnum;j++) printf("%-5d ",Net->arcs[i][j]); printf("\n"); } } void CreateDN(AdjMatrix *Net) { int i,j,k; int weight; VertexData v1,v2; printf("请输入图的顶点数和弧数:"); scanf("%d%d",&Net->vexnum,&Net->arcnum); for(i=0;i<Net->vexnum;i++) for(j=0;j<Net->vexnum;j++) { Net->arcs[i][j].adj=0; } printf("请输入图的顶点:\n"); for(i=0;i<Net->vexnum;i++) scanf("%d",&Net->vexs[i]); printf("请输入一条弧的两个顶点及权值:\n"); for(k=0;k<Net->arcnum;k++) { scanf("%d%d%d",&v1,&v2,&weight); Net->arcs[v1-1][v2-1].adj=weight; Net->arcs[v2-1][v1-1].adj=weight; if((v1+v2)==0)break; } for(i=0;i<Net->vexnum;i++) for(j=0;j<Net->vexnum;j++) { if(i!=j&&Net->arcs[i][j].adj==0) Net->arcs[i][j].adj=32767; } } int FirstVex(AdjMatrix *G,int k) { if(k>=0&&k<G->vexnum) { for(int i=0;i<G->vexnum;i++) if(G->arcs[k][i].adj!=INFINITY) return i; } return -1; } int NextVex(AdjMatrix *G,int i,int j) { if(i>=0 && i<G->vexnum && j>=0 && j<G->vexnum) { for(int k=j+1;k<G->vexnum;k++) if(G->arcs[i][k].adj!=INFINITY) return k; } return -1; } void DFS(AdjMatrix *G,int k) { int i; int v(G->vexs[max]); if(k==-1){ for(i=0;i<G->vexnum;i++) if(!visited[i]) DFS(G,i); } else{ visited[k]=true; printf("%d ",G->vexs[k]); for(i=FirstVex(G,k);i>=0;i=NextVex(G,k,i)) if(!visited[i]) DFS(G,i); } } void main() { AdjMatrix *Net=new AdjMatrix; CreateDN(Net); PrintDN(Net); visited=(bool*)malloc(Net->vexnum*sizeof(bool)); printf("n深度优先遍历: "); for(int i=0;i<Net->vexnum;i++) visited[i]=0; DFS(Net,-1); printf("\n"); }
Powered by: 博客园 Copyright © 2024 little健健 Powered by .NET 9.0 on Kubernetes