赞
踩
图的深度优先遍历递归算法(输出到文件)----C语言实现
- #include <stdio.h>
- #define MaxVex 100 //最大顶点数
- #define MaxNum 65535 //表示∞
- #define TRUE 1
- #define FALSE 0
- typedef char VertexType; //顶点类型
- typedef int EdgeType; //权值类型
- typedef int Bool;
- Bool visited[MaxVex];
- typedef struct {
- VertexType vexs[MaxVex]; //顶点数组
- EdgeType arc[MaxVex][MaxVex]; //邻接矩阵
- int numVertexes, numEdges; //当前图中的结点数以及边数
- }MGraph;
- //建立图的邻接矩阵
- void CreateMGraph(MGraph *G)
- {
- int i, j, k, w;
- printf("输入顶点数和边数: ");
- scanf("%d%d", &G->numVertexes,&G->numEdges);
- fflush(stdin);//清空缓冲区,并且可以换行
- printf("==============================\n");
- printf("输入各个顶点:\n");
- for (i=0; i<G->numVertexes; ++i)
- {
- printf("顶点%d: ",i+1);
- scanf("%c", &G->vexs[i]);
- fflush(stdin);
- }
-
- for (i=0; i<G->numVertexes; ++i)
- {
- for (j=0; j<G->numVertexes; ++j)
- G->arc[i][j] = MaxNum;
- }
-
- printf("==============================\n");
- for (k=0; k<G->numEdges; ++k)
- {
- printf("输入边(vi, vj)中的下标i和j和权W: ");
- scanf("%d%d%d", &i,&j,&w);
- G->arc[i][j] = w;
- G->arc[j][i] = G->arc[i][j];
- }
- }
- //图的深度优先遍历
- void DFS(MGraph G, int i)
- {
- FILE *pf;
- pf=fopen("333.txt","a+");
- int j;
- visited[i] = TRUE;
- fprintf(pf,"%c ",G.vexs[i]);
- printf("%c ", G.vexs[i]);
- for (j=0; j<G.numVertexes; ++j)
- {
- if (G.arc[i][j]!=MaxNum && !visited[j])
- DFS(G, j);
- }
- }
-
- void DFSTraverse(MGraph G)
- {
- int i;
- for (i=0; i<G.numVertexes; ++i)
- visited[i] = FALSE;
-
- for (i=0; i<G.numVertexes; ++i)
- {
- if (!visited[i])
- DFS(G, i);
- }
-
- }
- //程序入口
- int main(){
- FILE *pf;
- pf=fopen("333.txt","w");
- MGraph G;
- CreateMGraph(&G);
- printf("\n图的深度优先遍历为: ");
- DFSTraverse(G);
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。