您的位置:首页 > 编程语言 > C语言/C++

c语言描述之广度优先搜索——无权最短路径

2015-09-04 16:38 447 查看
广度优先搜索(bfs)是图遍历的一种方式,广度优先搜索的方法是从一个初始点v1开始,依次遍历所有与v1相邻且没有被标记的所有顶点,之后通过把相邻的顶点(v2,v3,v4)作为下一条边开始的顶点。循环遍历,直至所有节点都被遍历为止。



广度优先搜索很像是树的层序遍历。

#ifndef _adja_h
#define _adja_h

struct Node;
typedef struct Node *PNode;
typedef struct Node
{
int x;
PNode next;
}*EdgeNode;
typedef struct vertex 
{
int adjvex;
EdgeNode ele[12];
}*List;

void Adja(List L)
{
EdgeNode S;
int i,j,k;
printf("please input information");
for(k=1;k<=12;k++)
	L->ele[k]=NULL;
while(i!=0&&j!=0)
{
	scanf("%d%d",&i,&j);
	S=malloc(sizeof(struct Node));
	S->x=j;
	S->next=L->ele[i];
	L->ele[i]=S;	
}
}
#endif
为了方便以后使用邻接表,我把其设为了头文件,我建议设为头文件以后方便实用。

#include <stdio.h>
#include <stdlib.h>
#include "adja.h"

typedef struct TableEntry
{
int Known;/*标记,判断当前顶点是否被遍历*/
int Dist;/*距离,当前顶点与开始顶点的距离*/
int Path;/*与当前节点连接构成边的顶点*/
}*info;
typedef struct array
{
info arr[12];
}*Table;

void Initialize(Table T) /*初始化*/
{
int i;
for(i=1;i<=12;i++)
{
	T->arr[i]=(info)malloc(sizeof(struct TableEntry));	
	T->arr[i]->Known=0;
	T->arr[i]->Dist=15;
	T->arr[i]->Path=0;
}
}
void unweighed(Table T)
{
int *A;
List L;
L=(struct vertex *)malloc(sizeof(struct vertex));
Adja(L);/*引用邻接表*/
int i,j,k,n;
T->arr[1]->Dist=0;
for(k=0;k<=5;k++)
	for(j=1;j<=12;j++)
	{	
		i=1;/*随着j的变更,让i重置,方便数组A[]存储顶点j的信息*/
		if(T->arr[j]->Known==0&&T->arr[j]->Dist==k)
		{	
			T->arr[j]->Known=1;
              /*寻找j的邻接顶点*/
              while(L->ele[j]!=NULL)
			{
				A[i]=L->ele[j]->x;
				i++;
				L->ele[j]=L->ele[j]->next;
			}
			for(n=1;n<i;n++)
			{
				T->arr[(A
)]->Dist=k+1;							
                   T->arr[(A
)]->Path=j;
			}			
		}
	}
}
int main()
{
Table T;
int i,j;
T=malloc(sizeof(struct array));
Initialize(T);
unweighed(T);
for(i=1;i<=12;i++)
printf("%d的距离%d\n",i,T->arr[i]->Dist);
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: