数据结构
三个结构体,边,顶点,图。
typedef struct Side//边
{
int toVertex;//边指向的点
struct side *next;
}Side,*sLink;
typedef struct Vertex//顶点
{
int data;
sLink first;//第一个边
}Vertex,AdjList[20];
typedef struct Graph//图
{
AdjList adj;//顶点数组,注意不是指针,用.不用->
int n,v;//顶点数,边数
}Graph,*gLink;
创建
先顶点,再边。边用头插法,最后插的接在first上
void createGraph(gLink g)
{
int n,v,data;
printf("请输入顶点数与边数");
scanf("%d %d",&n,&v);
g->n = n;
g->v = v;
int i;
for(i=0;i
{
printf("请输入顶点%d权值",i);
scanf("%d",&data);
g->adj[i].data = data;
g->adj[i].first = NULL;
}
printf("请输入边信息");
int v1,v2;
for(i=0;i
{
scanf("%d %d",&v1,&v2);
sLink s = (sLink)malloc(sizeof(Side));
s->toVertex = v2;
s->next = g->adj[v1].first;
g->adj[v1].first = s;
}
}
遍历
第一个for初始化vidited,第二个for调用BFS或DFS。考虑到图可能不连通,所以用到第二个for。
void travel(gLink g)
{
int visited[g->n];
int i;
for(i=0;in;i++)
{
visited[i]=0;
}
for(i=0;in;i++)
{
if(!visited[i])
{
//DFS(g,visited,i);
BFS(g,visited,i);
}
}
}
深度优先搜索
递归
void DFS(gLink g,int *visited,int i)
{
visited[i] = 1;
printf("%-5d",g->adj[i].data);
sLink s = g->adj[i].first;
while(s)
{
if(!visited[s->toVertex])
{
DFS(g,visited,s->toVertex);
}
s = s->next;
}
}
广度优先搜索
用队列,类似于树的层序遍历
void BFS(gLink g,int *visited,int i)
{
Vertex queue[20];//队列
int rear=0,front=0;
queue[rear++] = g->adj[i];
visited[i]=1;
while(front!=rear)
{
Vertex v = queue[front++];//出队
printf("%-5d",v.data);
sLink s = v.first;
while(s)
{
if(!visited[s->toVertex])
{
queue[rear++] = g->adj[s->toVertex];//入队
visited[s->toVertex]=1;
}
s=s->next;
}
}
}
主函数
int main()
{
gLink g = (gLink)malloc(sizeof(Graph));
createGraph(g);
travel(g);
return 0;
}