广度优先搜索算法(BFS):
#include <stdio.h>
#include <string.h>
const int GNumber = 8;
int G[GNumber][GNumber];
int visit[GNumber];// 防止回环
struct Queue//用数组模拟队列
{
int queue[GNumber];
int start;
int end;
}MyQueue;
void BFS(int G[][GNumber], int n)
{
int j;
MyQueue.queue[MyQueue.end++] = 0;
visit[0] = 1;
while(MyQueue.end != MyQueue.start)
{ //color[MyQueue.start] = 1;
for(j=0; j<n; j++)
{
if(G[MyQueue.start][j] && !visit[j])
{
visit[j] = 1;
MyQueue.queue[MyQueue.end++] = j;
}
}
printf(" V%d ", MyQueue.queue[MyQueue.start++]+1);
}
}
int main(int argc, char **argv)
{
FILE *fr;
int i,j;
fr = fopen("dfs.txt","r");
if(!fr)
{
printf("fopen failed\n");
return -1;
}
while(fscanf(fr,"%d%d", &i, &j) != EOF)
{
G[i-1][j-1] = 1;
G[j-1][i-1] = 1;
}
memset(&MyQueue, 0, sizeof(MyQueue));
memset(visit, 0, sizeof(visit));
BFS(G,GNumber);
getchar();
return 0;
}