BFS-圖的廣度優先搜尋--鄰接矩陣

路漫漫之大神之養成發表於2016-04-11
# include <stdio.h>
# include <malloc.h>
# include <memory.h>


# define MAX 20		//最大頂點數 


typedef struct
{
	char vexs[MAX];		//頂點向量 
	bool visited[MAX];		//訪問標誌陣列 
	int arcs[MAX][MAX];		//鄰接矩陣 
	int arcnum,vexnum;		//圖的當前頂點數和弧數 
}MGRAPH, *mgraph;


void init_mgraph(mgraph &g)		//初始化圖 
{
	g = (mgraph)malloc(sizeof(MGRAPH));
	g->vexnum = 0;
	g->arcnum = 0;
	memset(g->vexs,0,sizeof(char)*MAX);
	memset(g->visited,false,sizeof(bool)*MAX);		//訪問標誌陣列為false時,未訪問 
	for (int i=0;i<MAX;++i)
	{
		for (int j=0;j<MAX;++j)
		{
			g->arcs[i][j] = 0;
		}
	}
}


void add_vexs(mgraph &g)		//增加頂點 
{
	printf ("請輸入頂點的個數\n");
	scanf ("%d",&g->vexnum);
	printf ("請輸入頂點的資訊\n");
	for (int i=0;i<g->vexnum;++i)
	{
		scanf (" %c",&g->vexs[i]);
	}
}


void add_arcs(mgraph &g)		//增加邊 
{
	printf ("請輸入邊的個數\n");
	scanf ("%d",&g->arcnum);
	char ch1,ch2;
	int row,col;
	printf ("請輸入邊的資訊\n");
	for (int i=0;i<g->arcnum;++i)
	{
		scanf (" %c %c",&ch1,&ch2);
		for (int j=0;j<g->vexnum;++j)
		{
			if (g->vexs[j] == ch1)
			{
				row = j;
			}
			if (g->vexs[j] == ch2)
			{
				col = j;
			}
		}
		g->arcs[row][col] = 1;
		g->arcs[col][row] = 1;			//無向圖加上此行 
	}
}


void creat_mgraph(mgraph &g)	//	建立圖 
{
	add_vexs(g);
	add_arcs(g);
}


void print_mgraph(mgraph &g)		//輸出圖 
{
	int i,j;
	printf ("   ");
	for (i=0; i<g->vexnum; ++i)
	{
		printf ("%3c",g->vexs[i]);
	}
	printf ("\n");
	for (i=0; i<g->vexnum; ++i)
	{
		printf ("%3c",g->vexs[i]);
		for (j=0; j<g->vexnum; ++j)
		{
			printf ("%3d",g->arcs[i][j]);
		}
		printf ("\n");
	}
	printf ("\n");
}


void visit(mgraph &g,int i)
{
	printf ("%c ",g->vexs[i]);
	g->visited[i] = true;
}


void BFStraverse(mgraph &g,int i)		//廣度優先搜尋 
{										//從第i個結點可是搜尋 
	int quene[MAX];			//輔助 佇列 
	memset(quene;0;sizeof(int)*MAX);
	int front = 0;		//頭指標 
	int rear = 0;		//尾指標 
	int gettop;		//取隊頭,節點編號	 
	
	visit(g,i);
	quene[rear++] = i;		//入對 
	
	while(front != rear)		//佇列非空 
	{
		gettop = quene[front++];		//出隊 
		for (int j=0; j<g->vexnum; ++j)
		{
			if (g->arcs[gettop][j] && !g->visited[j])
			{
				visit(g,j);
				quene[rear++] = j;		//入隊 
			}
		}
	}
}


int main (void)
{
	mgraph g;
	init_mgraph(g);
	creat_mgraph(g);
	print_mgraph(g);
	BFStraverse(g,0);
	
	return 0;
}

相關文章