迷宫游戏

链接:https://www.nowcoder.com/acm/contest/93/D
来源:牛客网

题目描述
给你一个n*m的迷宫,这个迷宫中有以下几个标识:

s代表起点

t代表终点

x代表障碍物

.代表空地

现在你们涵哥想知道能不能从起点走到终点不碰到障碍物(只能上下左右进行移动,并且不能移动到已经移动过的点)。

输入描述:
输入第一行一个整数T(1<=T<=10)
接下来有T组测试数据,对于每一组测试数据,第一行输入2个数n和m(1<=n,m<=500)
接下来n行,每行m个字符代表这个迷宫,每个字符都是上面4个中的一种
数据保证只有一个起点和一个终点
输出描述:
对于每一组测试数据,如果可以的话输出YES,不可以的话输出NO

示例1
输入
1
3 5
s…x
x…x
…tx
输出
YES

#include<iostream>
#include<queue>
using namespace std;
#define MAX 510
int dis[MAX][MAX];
const int INF = 10000000;
typedef pair<int, int> P;

int dx[4] = { 1,0,-1,0 };
int dy[4] = { 0,-1,0,1 };

char map[MAX][MAX];


int main()
{
    int sx, sy;//start
    int gx, gy;//end
    int i,n, m,j;
    int T;
    cin >> T;
    queue<P> que;
    while (T--)
    {
        cin >> n >> m;
        for (i = 0; i < n; i++)
        {
            for (j = 0; j < m; j++)
            {
                cin >> map[i][j];
                dis[i][j] = INF;
            }
        }
        for (i = 0; i < n; i++)
        {
            for (j = 0; j < m; j++)
            {
                if (map[i][j] == 's')
                {
                    sx = i; sy = j;
                    break;
                }
                if (map[i][j] == 't')
                {
                    gx = i; gy = j;
                    break;
                }
            }
        }
        //cout << gx << gy << endl;
        que.push(P(sx, sy));
        while (que.size())
        {
            P p = que.front(); que.pop();
            if (p.first == gx && p.second == gy) break;
            for (i = 0; i < 4; i++)
            {
                int nx = p.first + dx[i], ny = p.second + dy[i];
                if (nx >= 0 && nx < m&&ny >= 0 && ny < m&&map[nx][ny] != 'x'&&dis[nx][ny] == INF)
                {
                    que.push(P(nx, ny));
                    dis[nx][ny] = dis[p.first][p.second] + 1;
                }
            }
        }
        if (dis[gx][gy] != INF)cout << "YES" << endl;
        else cout << "NO" << endl;
    }

    //stem("pause");



    return 0;
}

猜你喜欢

转载自blog.csdn.net/weifuliu/article/details/79826245
今日推荐