sicily 无路可逃

Description

唐僧被妖怪关在迷宫中。孙悟空好不容易找到一张迷宫地图,并通过一个魔法门来到来到迷宫某个位置。假设迷宫是一个n*m的矩阵,它有两种地形,1表示平地,0表示沼泽,孙悟空只能停留在平地上。孙悟空目前的位置在坐标(sx,sy)处,他可以向上下左右四个方向移动。
请你帮助孙悟空计算一下,迷宫中是否存在一条路从他所在位置(sx,sy)到达唐僧所在位置(tx,ty)?

Input

输入第一行为一个整数t(0< t <=10),表示测试用例个数。

每个测试样例的第1行是2个正整数n (1≤n≤100),m (1≤n≤100),表示迷宫是n*m的矩阵。接下来的n行输入迷宫,每行有m个数字(0或者1),数字之间用一个空格间隔。
接下来的1行是4个整数sx,sy,tx,ty,1≤sx,tx≤n,1≤sy,ty≤m,表示孙悟空所在位置为第sx行第sy列,唐僧所在位置为第tx行第tx列。迷宫左上角编号是(1,1),右下角编号是(n, m)。
数据保证(sx,sy)格和(tx,ty)必定为平地。

Output

每个样例单独输出一行:1表示路径存在,0表示路径不存在。

Sample Input

2
2 2
1 0
0 1
1 1 2 2
4 4
1 1 1 0
1 0 1 1
1 0 1 1
1 1 1 0
1 1 3 4

Sample Output

0
1


说了那么多不就是用dfs走迷宫嘛= =正好拿来练练手。
由于偷懒就把一些东西设成全局变量了
这题对我来说最大的坑点可能就是因为我行列不分吧…找了好久的bug,最后互换了一下行和列就过了

代码:

#include <iostream>
#include <memory.h>
using namespace std;

struct position {
    int px;
    int py;
};

int maze[101][101];
int status[101][101];

int positionx[4] = {1, 0, -1, 0};           // turn right, down, left and up
int positiony[4] = {0, 1, 0, -1};

bool dfs(int col, int row, position start, position end) {
    for (int i = 0; i < 4; ++i) {
        position newpin;
        newpin.px = start.px + positionx[i];
        newpin.py = start.py + positiony[i];

        if (newpin.px == end.px && newpin.py == end.py)
            return true;

        if (newpin.px <= col && newpin.px >= 1 && newpin.py <= row && newpin.py >= 1)
            if (!status[newpin.px][newpin.py]) {
                status[newpin.px][newpin.py] = 1;
                if (maze[newpin.px][newpin.py])
                    if (dfs(col, row, newpin, end))
                        return true;
            }
    }
    return false;
}

int main() {
    int t;
    cin >> t;
    while (t--) {
        int m, n;
        cin >> n >> m;

        for (int i = 1; i <= n; ++i)            //initialize
            for (int j = 1; j <= m; ++j)
                cin >> maze[i][j];
        memset(status, 0, sizeof(status));

        position startpin, endpin;
        cin >> startpin.px >> startpin.py;
        cin >> endpin.px >> endpin.py;

        if (startpin.px == endpin.px && startpin.py == endpin.py) {
            cout << 1 << endl;
            continue;
        }
        if (dfs(n, m, startpin, endpin))
            cout << 1 << endl;
        else
            cout << 0 << endl;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值