鄰接矩陣和鄰接表的深度優先遍歷

//風雨難洗心痕,滄桑不滅情傷。莫要輕言亙古,離散纔看荒涼。


#include "stdio.h"
typedef char Vertextype;  //頂點
typedef int EdgeType;  //邊的權值
typedef int Boolean;
Boolean visited[MAXVEX];//訪問標誌的數組
#define MAXVEX 100
#define INFINITY 65535






//鄰接矩陣
typedef struct
{
Vertextype vexs[MAXVEX];  //頂點表
EdgeType arc[MAXVEX][MAXVEX];//鄰接矩陣,可以看做邊表
int numvertexes, numEdges;  //當前的頂點和邊數
}MGraph;




void DFS(MGraph G, int)
{
int i;
visited[MAXVEX] = true;
printf("%c", G.vexs[i]);//也可以其他操作
for (int j = 0; j < G->numvertexes; j++)
{
if (G.arc[i][j] == 1 && !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);
}
}








//鄰接表
typedef struct EdgeNode  //邊表結點
{
int adjvex;//鄰接頂點
EdgeType weight;  //存儲權值
struct EdgeNode *next;//用來指向下一個鄰接點
}EdgeNode;


typedef struct VertexNode  //頂點表結點
{
Vertextype data;//頂點
EdgeNode *firstedge;//邊表頭指針
}VertexNode, AdjList[MAXVEX];


typedef struct
{
AdjList adjList;
int numVertexes, numEdgES;//當前的頂點和邊
}GraphAdjList;




void DFS1(GraphAdjList GL, int i)
{
EdgeNode *p;
visited[i] = true;
printf("%c", GL.adjList[i].data);
p = GL.adjList[i].firstedge;
while (p)
{
if (!visited[p->adjvex])
DFS1(GL, i);
p = p->next;
}
}


void DFSTraverse1(GraphAdjList GL)
{
int i;
for ( i = 0; i < GL.numVertexes; i++)
{
visited[i] = false;
}
for ( i = 0; i < GL.numVertexes; i++)
{
if (!visited[i])
DFS1(GL, i);
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章