/** 测试用例数据结构 陈越 第二版 P219 6.2
* 8
* 9
* 0 1 1
* 1 2 1
* 2 3 1
* 3 0 1
* 0 4 1
* 4 5 1
* 5 6 1
* 6 7 1
* 7 4 1
* A B C D E F G H
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MaxVertexNum 100
#define INFINITY 65535
typedef int Vertex; /**< 用顶点下标表示顶点,一般用两个vertex表示一个顶点 */
typedef int WeightType;
typedef char DataType;
/**< 图结点的定义 */
typedef struct GNode * PtrToGNode;
struct GNode
{
int Nv;
int Ne;
WeightType G[MaxVertexNum][MaxVertexNum];
DataType Data[MaxVertexNum];
};
typedef PtrToGNode MGraph;
/**< 边的定义 */
typedef struct ENode * PtrToENode;
struct ENode
{
Vertex v1, v2;
WeightType Weight;
};
typedef PtrToENode Edge;
bool visited[MaxVertexNum];/**< 是否已经访问的标记 */
/**< 初始化一个有VertexNum个顶点,边数为0的图 */
MGraph CreatGraph(int VertexNum);
MGraph CreatGraph(int VertexNum)
{
Vertex i, j;
MGraph Graph;
Graph = (MGraph)malloc(sizeof(struct GNode));
Graph->Nv = VertexNum;
Graph->Ne = 0;
for(i=0; i<VertexNum; i++)
{
visited[i] = false; /**< 把访问标记默认设置为false */
for(j=0; j<VertexNum; j++)
{
Graph->G[i][j] = INFINITY;
}
}
return Graph;
}
void InsertEdge(MGraph Graph, Edge E);
void InsertEdge(MGraph Graph, Edge E)
{
Graph->G[E->v1][E->v2] = E->Weight;
/**< 无向图需要插入逆方向的权重值,若是有向图则无须以下语句 */
Graph->G[E->v2][E->v1] = E->Weight;
}
/**< 这里的build其实就是平时main里面做的东西 */
MGraph BuildGraph();
MGraph BuildGraph()
{
MGraph Graph;
Edge E;
Vertex V;
int Nv, i;
scanf("%d", &Nv); /**< 读入顶点个数 */
Graph = CreatGraph(Nv);
scanf("%d", &(Graph->Ne));
{
printf("Number of Edge:%d\n", Graph->Ne);
}
if(Graph->Ne>0)
{
E = (Edge)malloc(sizeof(struct ENode));
for(i=0 ;i<Graph->Ne; i++)
{
scanf("%d %d %d", &E->v1, &E->v2, &E->Weight);
InsertEdge(Graph, E);
}
}
/**< 若然还有数据 */
char ch;
for(i=0; i<Graph->Nv; i++)
{
while((ch=getchar())==' '||ch=='\n'){};
Graph->Data[i] = ch;
visited[i] = false;
}
return Graph;
}
void DFSprint(MGraph Graph, Vertex i);
void DFSprint(MGraph Graph, Vertex i)
{
printf("%c\t", Graph->Data[i]);
}
void DFS(MGraph Graph, Vertex i);
void DFS(MGraph Graph, Vertex i)
{
visited[i] = true;
DFSprint(Graph, i);
int j;
for(j=0; j<Graph->Nv; j++)
{
if(Graph->G[i][j]!=INFINITY && !visited[j])
{
DFS(Graph, j);
}
}
}
int main()
{
int i;
MGraph g;
g = BuildGraph();
DFS(g, 4);
system("pause");
}
邻接矩阵形式图的深度优先搜索
最新推荐文章于 2023-12-05 09:10:12 发布