宽度优先示例

本文介绍了一种基于广度优先搜索(BFS)的迷宫求解算法,通过使用队列数据结构来追踪路径,从起点出发逐步探索迷宫直到找到终点。详细解释了算法的实现过程,包括初始化队列、加入起点、遍历邻居节点并更新距离等关键步骤。此外,还展示了算法如何在二维矩阵上进行操作,并通过示例输出了最短路径的长度及整个迷宫的访问状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



#include <stdio.h>
#include <string.h>
typedef struct
{
    int x,y;
    int sec;
}point;

typedef struct
{
    point a[12000];
    int front,rear;
    int size;
}que;
que q;
int row,col, count;
int map[102][102];
int dire[4][2] = {{0,1}, {1,0}, {0,-1}, {-1,0}};
point start, now;

void init_que()
{
    q.front = q.rear= q.size = 0;
}
void in_que(point p)
{
    q.a[q.rear] = p;
    q.rear = (q.rear+1)%12000;
    q.size++;
}

void de_que(point *p)
{
//  *p = q.a[q.front];
    p->x= q.a[q.front].x;
    p->y= q.a[q.front].y;
    p->sec = q.a[q.front].sec;
    q.front = (q.front+1)%12000;
    q.size--;
}

void broadfs()
{
    point p,tmp;
    int i,flag;
    while(q.size > 0)
    {
        de_que(&p);
        for(i = 0; i < 4; i++)
        {
            tmp.x = p.x+dire[i][0];
            tmp.y = p.y+dire[i][1];
            if(map[tmp.x][tmp.y] == 1)
            {
                now = tmp;
                map[now.x][now.y] = p.sec+1;
                now.sec = p.sec+1;
                in_que(now);
            }
        }
    }
}

int main(void)
{
    int tc, T, i,j;


     //freopen("input.txt", "r", stdin);

    setbuf(stdout, NULL);

    scanf("%d", &T);
    for(tc = 0; tc < T; tc++)
    {
        scanf("%d %d", &col, &row);
        memset(map, 0, sizeof(map));
        for(i = 1; i <= row; i++)
        {
            for(j = 1; j <= col; j++)
            {
                scanf("%d", &map[i][j]);
            }
        }
        scanf("%d %d", &start.x, &start.y);
        map[start.x][start.y] = 0;
        init_que();
        start.sec = 1;
        in_que(start);

        broadfs();
        printf("%d\n", now.sec);
        for(i = 1; i <= row; i++)
        {
            for(j = 1; j <= col; j++)
            {
                printf("%3d", map[i][j]);
            }
            printf("\n");
        }
        printf("\n");
    }

    return 0;//Your program should return 0 on normal termination.
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值