• BFS经典模板


    代码

    #include <stdio.h>
    
    #define SIZE 51
    struct node
    {
        int x;//横坐标
        int y;//纵坐标
        int f;//父亲在队列中得编号
        int s;//步数
    };
    
    int main()
    {
        struct node que[SIZE*SIZE+1];//保存结点队列
        
        int data[SIZE][SIZE] = {0};
        int book[SIZE][SIZE] = {0};
        
        //定义一个用于表示走的方向的数组
        int next[4][2] = {
            {0,1},//向右
            {1,0},//向下
            {0,-1},//向左
            {-1,0},//向上
        };
        
        int head,tail;
        
        int i,j,k,n,m,startx,starty,endx,endy,tx,ty,flag;
        
        //读取矩阵数据
        scanf("%d %d",&n, &m);
        for (i=1; i<=n; i++) {
            for (j=1; j<=m; j++) {
                scanf("%d",&data[i][j]);
            }
        }
        
        //读取起始点,终点
        scanf("%d %d %d %d", &startx, &starty, &endx, &endy);
        
        //队列初始化
        head = 1;
        tail = 1;
        
        //往队列插入起始坐标信息
        que[tail].x = startx;
        que[tail].y = starty;
        que[tail].f = 0;
        que[tail].s = 0;
        tail++;
        
        book[startx][starty] = 1;
        
        flag = 0;//用来标记是否到达目标点,0:未到达 1:到达
        
        //当队列不为空得时候循环
        while (head < tail) {
            //枚举4个方向
            for(k=0;k<4;k++)
            {
                //计算下一个坐标点
                tx = que[tail].x + next[k][0];
                ty = que[tail].y + next[k][1];
                
                //判断是否越界
                if(tx<1 || tx>n || ty<1 || ty>m)
                    continue;
                
                //判断数据是否有效,或者该结点是否已经在路径中
                if (data[tx][ty] == 0 && book[tx][ty]==0) {
                    
                    //标记这个点已经走过,并插入新的点到队列中
                    book[tx][ty] = 1;
                    que[tail].x = tx;
                    que[tail].y = ty;
                    que[tail].f = head;//因为该点是从head扩展出来的,所以他的父亲是head
                    que[tail].s = que[head].s + 1;//步数是父亲的步数+1
                    
                    tail++;
                }
                
                //如果到目标点了,则停止扩展,任务结束,退出循环
                if (tx == endx && ty == endy) {
                    flag = 1;
                    break;
                }
            }
            
            if (flag == 1) {
                break;
            }
            
            head++;//当一个点扩展结束后,head++才能对后面的点再进行扩展
        }
        
        //打印队列中末尾最后一个点(目标点)的步数
        //注意:tail是指向队列队尾的下一个位置,所以需要-1
        printf("%d",que[tail-1].s);
        
        return 0;
    }
  • 相关阅读:
    博客园设置自定义壁纸 模板
    html常用标签及属性,常用英语单词
    解释器安装与环境变量的添加
    计算机基础知识
    python 标准库大全
    进程的状态转换详解
    python 合集set,交集,并集,差集,对称差集别搞混
    vue组件,可以通过npm引用的组件
    use vue vuex vue-router, not use webpack
    Webpack+Vue如何导入Jquery和Jquery的第三方插件
  • 原文地址:https://www.cnblogs.com/monkeyvera/p/4382439.html
Copyright © 2020-2023  润新知