算法之BFS（广度优先搜索算法）

``</pre><pre>``

``````#include<stdio.h>

/*有8个城市，编号分别为0~7，求从0号城市到7号城市的最短路线*/
int jz[8][8]= { {0,1,1,1,0,1,0,0},
{1,0,0,0,0,1,0,0},
{1,0,0,1,1,0,0,0},
{1,0,1,0,0,0,1,0},
{0,0,1,0,0,0,1,1},
{1,1,0,0,0,0,0,1},
{0,0,0,1,1,0,0,1},
{0,0,0,0,1,1,1,0}};//0表示不能走，1表示可行

struct
{
int city,pre;
} sq[100];

int qh,qe,i,visited[100];

void out()
{
printf("%d",sq[qe].city);
while(sq[qe].pre!=0)
{
qe=sq[qe].pre;
printf("--%d",sq[qe].city);
}
}

void search(int n)
{
qh=0;
qe=1;
sq[1].city=0;
sq[1].pre=0;
visited[1]=1;
while(qh!=qe)   //当队不为空
{
qh=qh+1;    //结点出队
for(i=0;i<n;i++)
if(jz[sq[qh].city][i]==1&&visited[i]==0)  //如果从城市sq[qh].city可以直接到达城市i，且城市i没有访问过
{
qe=qe+1;//结点入队
sq[qe].city=i;
sq[qe].pre=qh;
visited[i]=1;
if(sq[qe].city==7)
{
out();
return ;
}
}

}
printf("No Solution!\n");
}

int main()
{
int i,n;
n=8;
for(i=0;i<n;i++)
visited[i]=0;
search(n);

return 0;
}``````

``````/*迷宫如下，1表示墙，0表示路
0 0 0 0 0 0 0 0
0 1 1 1 1 0 1 0
0 0 0 0 1 0 1 0
0 1 0 0 0 0 1 0
0 1 0 1 1 0 1 0
0 1 0 0 0 0 1 1
0 1 0 0 1 0 0 0
0 1 1 1 1 1 1 0
*/

#include<stdio.h>
/*储存迷宫矩阵*/
int maze[8][8]={{0,0,0,0,0,0,0,0},
{0,1,1,1,1,0,1,0},
{0,0,0,0,1,0,1,0},
{0,1,0,0,0,0,1,0},
{0,1,0,1,1,0,1,0},
{0,1,0,0,0,0,1,1},
{0,1,0,0,1,0,0,0},
{0,1,1,1,1,1,1,0}};

/*定义方向数组，如：i+fx[0],j+fy[0],表示向下移动*/

int fx[4]={1,-1,0,0};
int fy[4]={0,0,-1,1};

struct {
int x,y,pre;
}sq[100];

int qh,qe,i,j,k;

void out()
{
printf("(%d,%d)",sq[qe].x,sq[qe].y);
while(sq[qe].pre!=0)
{
qe=sq[qe].pre;
printf("--(%d,%d)",sq[qe].x,sq[qe].y);
}
}
int check(int i,int j)
{
int flag=1;
if(i<0||i>7||j<0||j>7)//是否在迷宫内
flag=0;
if(maze[i][j]==1||maze[i][j]==-1) //是否可行
flag=0;
return flag;
}

void search()
{
qh=0;
qe=1;
maze[0][0]=-1;//表示访问过
sq[1].pre=0;
sq[1].x=0;
sq[1].y=0;
while(qh!=qe)//当队不为空
{
qh=qh+1; //出队
for(k=0;k<4;k++)//搜索可达到的方块
{
i=sq[qh].x+fx[k];
j=sq[qh].y+fy[k];
if(check(i,j)==1)
{
qe=qe+1;//入队
sq[qe].x=i;
sq[qe].y=j;
sq[qe].pre=qh;
maze[i][j]=-1;//表示访问过
if(sq[qe].x==7&&sq[qe].y==7)
{
out();
return ;
}

}
}
}
printf("No Solution!\n");
}
int main()
{
search();
return 0;
}

``````

PS:每天学到一点点，就很开心

原文作者：BFS
原文地址: https://blog.csdn.net/qq_31028891/article/details/53091583
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。