迷宫问题1

一天蒜头君掉进了一个迷宫里面,蒜头君想逃出去,可怜的蒜头君连迷宫是否有能逃出去的路都不知道。

看在蒜头君这么可怜的份上,就请聪明的你告诉蒜头君是否有可以逃出去的路。
输入格式

第一行输入两个整数 n和 m,表示这是一个 n×m 的迷宫。

接下来的输入一个 n 行 m 列的迷宫。其中 ‘S’ 表示蒜头君的位置,’*‘表示墙,蒜头君无法通过,’.‘表示路,蒜头君可以通过’.'移动,'T’表示迷宫的出口(蒜头君每次只能移动到四个与他相邻的位置——上,下,左,右)。
输出格式

输出一个字符串,如果蒜头君可以逃出迷宫输出"yes",否则输出"no"。
数据范围

1≤n,m≤10

输出时每行末尾的多余空格,不影响答案正确性
样例输入1

3 4
S**.
…*.
***T

样例输出1

no

样例输入2

3 4
S**.

***T

样例输出2

yes

#include <iostream>
#include <cstdio>
using namespace std;
int n, m;
bool f;
char mp[15][15];
int vis[15][15];
int dir[4][2] = {{-1, 0}, {0,1}, {1,0}, {0,-1}};
bool in(int x, int y){
    return 0<= x && x < n&& 0 <= y && y < m;
}
void dfs(int x, int y){
    if (mp[x][y] == 'T'){
        f = true;
        return;
    }
    if (!in(x,y)||mp[x][y]=='*'||vis[x][y]){
        return;
    }
    vis[x][y] = 1;
    for (int i = 0; i < 4; i++){
        int tx = x + dir[i][0];
        int ty = y + dir[i][1];
        dfs(tx,ty);
    }
    return;
}
int main(){
	scanf("%d%d", &n, &m);
    for(int i = 0; i < n; i++){
        scanf("%s", mp[i]);
    }
    int x, y;
    for(int i = 0; i < n; i++){
       for(int j = 0; j < m; j++){
           if (mp[i][j] == 'S'){
               x = i;
               y = j;
           }
       }
    }
    dfs(x, y);
    if (f){
        printf("yes\n");
    }else{
        printf("no\n");
    }
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41979221/article/details/88394697
今日推荐