迷宫plus

博客围绕求解n*m迷宫中起点到终点的最短距离展开,迷宫中'0'为路,'1'为墙,'2'为起点,'3'为终点。介绍了多实例测试的输入输出格式,还提及可使用队列和搜索两种方法来解决该问题。

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

题目描述

给定n*m的迷宫 (2<n,m<24) ,迷宫中'0'代表路,'1'代表墙,'2'代表起点,'3'代表终点,求起点到终点最短距离

输入

多实例测试
第一行输入n,m
下面是n行,每行输入m个字符

输出

输出起点到终点最短距离

样例输入

5 3
0 0 0
0 1 0
0 2 0
0 1 3
0 0 0

样例输出

2

提示

多组样例输入

输入保证有一条路从起点到终点

方法一:用队列 

 

#include <bits/stdc++.h>
using namespace std;
char ma[205][205];
int dir[][2]= {1,0,-1,0,0,1,0,-1};
int n,m;
struct ff
{
    int x,y,time;
    friend bool operator <(ff n1,ff n2)
    {
        return n2.time < n1.time;
    }
} p,s,t;
void bfs(int a,int b)
{
    priority_queue<ff>q;
    p.x=a,p.y=b,p.time=0;
    q.push(p);
    while(!q.empty())
    {
        s=q.top();
        q.pop();
        for(int i=0; i<4; i++)
        {
            t.x=s.x+dir[i][0];
            t.y=s.y+dir[i][1];
            if(t.x >= 0&&t.x < n && t.y >= 0&&t.y<m&& ma[t.x][t.y] != '1')
            {
                if(ma[t.x][t.y] == '3')
                {
                    printf("%d\n",s.time+1);
                    return ;
                }
                if(ma[t.x][t.y]=='0')
                {
                    t.time=s.time+1;
                }
                q.push(t);
                ma[t.x][t.y]='1';
            }
        }

    }
}
int main()
{
    int xx,yy;
    while(~scanf("%d%d",&n,&m))
    {
        for(int i=0; i<n; i++)
        {
            for(int j=0; j<m; j++)
            {
                cin>>ma[i][j];
                if(ma[i][j]=='2')
                {
                    xx=i;
                    yy=j;
                }
            }
        }
        bfs(xx,yy);
    }
    return 0;
}

 

方法二:搜索

#include <iostream>
using namespace std;
int map[30][30], vis[30][30], step = 0, minn = 100000, n, m;
int a[][2] = {1, 0, 0, 1, -1, 0, 0, -1};
void dfs(int x, int y, int step)
{
    if(map[x][y] == 3)
    {
        if(step < minn)
            minn = step;
        return;
    }

    for(int i = 0; i < 4; i++)
    {
        x += a[i][0];
        y += a[i][1];
        if(x >= 0 && y >= 0 && x < n && y < m && map[x][y] != 1 && vis[x][y] != 1)
        {
            step++;
            vis[x][y] = 1;
            dfs(x, y, step);
            step--;
            vis[x][y] = 0;
        }
        x -= a[i][0];
        y -= a[i][1];
    }
}
int main()
{
    int x, y;
    cin >> n >> m;
    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < m; j++)
        {
            cin >> map[i][j];
            if(map[i][j] == 2)
                x = i, y = j;
        }
    }
    dfs(x, y, 0);
    cout << minn << endl;
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值