算法之BFS(广度优先搜索算法)

来源:互联网 发布:类似淘宝联盟有返利的 编辑:程序博客网 时间:2024/06/05 23:55
</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 00 1 1 1 1 0 1 00 0 0 0 1 0 1 00 1 0 0 0 0 1 00 1 0 1 1 0 1 00 1 0 0 0 0 1 10 1 0 0 1 0 0 00 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:每天学到一点点,就很开心

0 0
原创粉丝点击