zcmu-1185: 走迷宫(dfs经典题)

版权声明:本人大三在读,有错误烦请指正,共同进步- ( ゜- ゜)つロ 乾杯~点赞请按右上角,转载请标明出处: https://blog.csdn.net/hzyhfxt/article/details/84310142

1185: 走迷宫

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 379  Solved: 153
[Submit][Status][Web Board]

Description

给一张个迷宫,问能否从起点走到终点,只能往上下左右走,不能斜着走

Input

多组测试数据,每组第一行两个正整数,分别为n和m

表示n这个迷宫有n行m列(0<n,m<10)

接着是n行m列,

'#'表示路

‘*’表示墙

‘S’表示起点

‘T’表示终点

Output

每组测试数据输出一个结果,如果能从S走到T,输出“YES”,否则输出“NO”

Sample Input

2 2 S* #T 3 3 S*# #*T ##*

Sample Output

YES NO

 n,m边界那里纠结了很久,还去问了同学,其实画一下就好了哈哈哈笨呆了

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <map>
#include <list>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
#include <iostream>
#define mem(a) memset(a,0,sizeof(a))
using namespace std;
typedef long long ll;
char c[15][15];
int flag = 0,n,m;
//往上、下、左、右走的时候x,y坐标的变化
int dx[] = {0,0,-1,1};
int dy[] = {-1,1,0,0};
int vis[15][15];
void dfs(int x,int y)
{
    vis[x][y] = 1;
    if(c[x][y] == 'T')//搜到了就停了
    {
        flag = 1;
        return;
    }
    for(int i = 0; i < 4;i++)//没搜到,就继续往四个方向搜
    {
        int x1 = x + dx[i];
        int y1 = y + dy[i];
        if(x1 >= 0 && y1 >= 0 && x1 < m && y1 < n && !vis[x1][y1] && c[x1][y1] != '*')//这里不能写 == ‘#’,我刚开始写错了,而且把x1,y1的范围nn,m弄反了
            dfs(x1,y1);
    }
}

int main()
{
    while(scanf("%d%d",&n,&m) != EOF)
    {
        int sx,sy;
        flag = 0;
        mem(vis);
        for(int i = 0;i < n;i ++)
        {
            getchar();//别忘记这个
            scanf("%s",c[i]);
        }
        for(int i = 0;i < n;i++)
        {
            for(int j = 0;j <m;j++)
            {
                if(c[i][j] == 'S')
                {
                    sx = i;
                    sy = j;
                    break;
                    
                }
            }
        }
        dfs(sx,sy);
        printf(flag ? "YES\n":"NO\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/hzyhfxt/article/details/84310142