# include <stdio.h>
# include <malloc.h>
# include <stdlib.h>
# include <memory.h>
# define ok 1
# define NULL 0
# define MAX 20 //最大頂點數
typedef struct ARCNODE
{
int adjvex; //該邊所指的頂點的位置
struct ARCNODE * next; //指向下一條邊的指針
// int weight; //有向圖邊的權
}arcnode,* node; //表的節點
typedef struct VNODE
{
char data; //頂點信息
node firstarc; //指向第一條依附該頂點的邊的弧指針
}vnode,adjlist[MAX]; //頭結點
typedef struct algraph
{
adjlist vertices;
int visited[MAX]; //訪問標誌數組
int vexnum,arcnum; //圖的當前頂點數和弧度
}mgraph;
void init_mgraph(mgraph &g) //初始化圖
{
memset(g.visited,0,sizeof(int)*MAX); //訪問標誌數字置0,表示沒有被訪問
// for (int i=0;i<MAX;++i)
// g.visited[i] = 0;
g.vexnum = 0;
g.arcnum = 0;
}
int locatevex(mgraph &g,char v) //查找頂點v在頂點向量中的位置
{
int i;
for (i=0; v!=g.vertices[i].data && i<g.vexnum; ++i)
;
if (i>=g.vexnum)
return -1;
return i;
}
void add_vex(mgraph &g) //增加節點
{
printf ("請輸入無向圖的頂點數\n");
scanf ("%d",&g.vexnum);
printf ("輸入頂點信息:\n");
for (int i=0;i<g.vexnum;++i)
{
scanf (" %c",&g.vertices[i].data); //構造頂點向量
g.vertices[i].firstarc = NULL;
}
}
void add_arc(mgraph &g) //增加邊
{
node s,t;
printf ("請輸入無向圖的邊數\n");
scanf ("%d",&g.arcnum);
char ch1,ch2;
printf ("輸入信息\n");
for (int k=0; k<g.arcnum; ++k)
{
scanf (" %c %c",&ch1,&ch2);
int i = locatevex(g,ch1);
int j = locatevex(g,ch2); //確定v1,v2在g中的位置
s = (node)malloc(sizeof(arcnode));
t = (node)malloc(sizeof(arcnode));
s->adjvex = j; //該邊所指向的頂點的位置爲j
s->next = g.vertices[i].firstarc;
g.vertices[i].firstarc = s;
t->adjvex = i; //該邊所指向的頂點的位置爲i;
t->next = g.vertices[j].firstarc;
g.vertices[j].firstarc = t;
}
}
void creat_mgraph(mgraph &g) //構造鄰接鏈表
{
add_vex(g); //增加節點
add_arc(g); //增加邊
}
void printadjlist(mgraph &g)
{
int i;
node p;
printf ("編號 頂點 鄰點編號\n");
for (i=0;i<g.vexnum;++i)
{
printf (" %d %c ",i,g.vertices[i].data);
for (p=g.vertices[i].firstarc;p;p=p->next)
printf ("%d ",p->adjvex);
printf ("\n");
}
}
void visit(mgraph &g,int i)
{
printf ("%c ",g.vertices[i].data);
g.visited[i] = 1;
}
void DFStraverse(mgraph &g,int i) //深度優化搜索
{ //從第i個頂點開始搜索
visit(g,i);
node p;
for ((p=g.vertices[i].firstarc); p ;(p=p->next))
if (!g.visited[p->adjvex])
DFStraverse(g,p->adjvex);
}
int main(void)
{
mgraph g;
init_mgraph(g);
creat_mgraph(g);
printadjlist(g);
DFStraverse(g,0);
return 0;
}
DFS--深度優先搜索--圖的鄰接表表示
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.