每日一题 No.10 迷宫问题(是否可达)

本题要求:

给定一个大小为n * m(n <= 100, m <= 100)的迷宫。迷宫由通道(0)和墙壁(#)组成,每一步可以向邻接的上下左右四格的通道移动。请求出从起点出发是否可以到达终点。

输入格式:

输入n、m、起点(x, y)、终点(x, y)
接下来n*m输入地图

输出格式:

可以到达输出”Yes”,否则输出“No”

输入样例:

5 5 0 0 3 3
0 # 0 0 0
0 0 # 0 #
0 0 # 0 #
0 # 0 0 0
0 # 0 # 0

输出样例:

Yes

解题思路 :

Created with Raphaël 2.1.0 函数开始 判断该点是否可以通过 判断该点是否是终点 找到终点,标记 函数结束 向4个方向的点探索 yes no yes no

代码 :

#include<iostream> 

using namespace std;

#define MAX 0x7f7f

char map[101][101];
int dist[101][101];
int n, m;
pair<int, int> start, end;
void dfs(pair<int, int> now, int last) {
    if (now.first < 0 || now.first >= n || now.second < 0 || now.second >=m || map[now.first][now.second] == '#') {
        return;
    }
    if (dist[now.first][now.second] > last + 1) {
        dist[now.first][now.second] = last + 1;
    } else {
        return;
    }
    dfs(pair<int, int>(now.first, now.second + 1), dist[now.first][now.second]);
    dfs(pair<int, int>(now.first + 1, now.second), dist[now.first][now.second]);
    dfs(pair<int, int>(now.first, now.second - 1), dist[now.first][now.second]);
    dfs(pair<int, int>(now.first -1, now.second), dist[now.first][now.second]);
}
int main() {
    cin >> m >> n;
    cin >> start.first >> start.second >> end.first >> end.second;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cin >> map[j][i];
        }
    }
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            dist[i][j] = MAX;
        }
    }
    dfs(start,-1);
    if (dist[end.first][end.second] ==MAX) {
        cout << "Yes";
    } else {
        cout << "No";
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值