阅读 62

数据结构先序遍历图解,有向图的拓扑序列怎么求

# include iostream # include time.h # include windows.h # includequeusingnamespacestd; # definenum 100 # pragma warning (disable :4996 ) typedef struct link{int index; 结构链接* next; }*Node,node; typedef struct Link{char word; 节点第一; (头,头; typedefstructg { headlinktable [ num ]; int n,e; (地图,地图; voidallocatemap(mapg; //为图指针分配图的独占区域voidparmmap(mapg ); //邻接表参数voidcreatemap(mapg ); //创建邻表标题intlocatev(mapg,char x ); //确定关系顶点位置的voidrelatemap(mapg ); //生成图的关系链voidprintmap(mapg ); //打印图旁边的表的voidsingledepthsearch(mapg,int n,int visited[] ); //从邻表的标题开始,Voiddepthsearch(mapg,int visited[] ) ) ) ) ) ) ) ) ) ) ) )//遍历所有邻表标题,这样就可以//从相邻表的一个标题开始进行宽搜索(此标题为voidwidespread(mapg,int visited[] ) ) ) )//遍历所有相邻表标题,现在int visited[NUM]={ 0 }; 地图g; 分配图(g ); parmmap(g ); 创建映射(g ); relatemap(g ); 打印图(g ); 深度搜索(g,visited ); idespread(g,Visited ); 返回0; }voidallocatemap(mapg ) /为图指针分配图的独占区域{G=new map; ) voidparmmap(mapg ) /传递给邻表的参数({cout )输入图表的基本参数,即图表的顶点数和边数。 ); cin G-n; cin G-e; }voidcreatemap(mapg ) /创建旁边的表头) {char a[NUM]; 请输入cout '顶点的具体数据: '; cin a; for(intI=0; i G-n; I ) {G-linktable[i].word=a[i]; G-linktable[i].first=NULL; }intlocatev(mapg,char x ) /确定关系顶点的位置) {int i; for(I=0; i G-n; I ) if(g-linktable[I].word==x ) return i; }return -1; }voidrelatemap(mapg ) /创建贴图的关系链({int j=0,k=0; char a,b; cout '请输入图的关系。' endl; for(intI=0; i G-e; I ) {cin a b; j=locatev(g,a ); k=locatev(g,b ); Node p=new node; p-index=k; p-next=G-linktable[j].first; G-linktable[j].first=p; }voidprintmap(mapg ) /打印图邻表) {cout图邻表为' endl; for(intI=0; i G-n; I ) {Node p=G-linktable[i].first; cout G-linktable[i].word '--- '; while(p ) ) {cout G-linktable[p-index].word; p=p-next; if(p ) cout '-- '; }cout endl; }voidsingledepthsearch(mapg,int n,int visited[] () ) /从邻表标题向下钻取以查找,直到完成此标题遍历Node p=G-linktable[n].first; cout G-linktable[n].word; while(p ) (if ) visited[p-index]==0) SingleDepthsearch(G ) g,p-index,visited ); p=p-next; }voiddepthsearch(mapg,int visited[] () ) /通过遍历所有相邻表的标头,在深度搜索({cout )深度优先搜索中遍历此图的结果为(); for(intI=0; i G-n; I ) if(visited[I]==0) singledepthsearch(g,I,visited ); }cout endl; ) voidsinglewidesearch(mapg,int n,int visited[] () ) /从邻表的标题开始进行宽搜索,直到完成对该标题的遍历) {visited[n]=1 queueint q; q.push(n ); cout G-linktable[n].word; while(q.empty(==false ) { node p=g-link table [ q.front ] ].first; while(p ) if ) visited[p-index]==0) {cout G-linktable[p-index].word; q.push(p-index ); visited[p-index]=1; (}p=p-next; (}q.pop ); }voidwidespread(mapg,int visited[] () ) /遍历所有相邻表的标头,从而通过宽搜索({cout )宽优先级搜索遍历此图,结果显示for(intI=0; i G-n; I ) if(visited[I]==0) singlewidesearch(g,I,visited ); }cout endl; }上图左图为有向图表示范例的逻辑结构图,右图为对应图表的邻接表

【注】:如果是有向图表,在输入图表关系时,按照双向输入的标准输入即可。 也就是说,一条连接线表示双向连接

下图是相应代码的执行结果


文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐