hihoCoder - 1519 : 逃离迷宫II(宽搜)

1519 : 逃离迷宫II

时间限制:10000ms
单点时限:1000ms
内存限制:256MB

描述

小Hi被坏女巫抓进里一间有N x M个格子组成的矩阵迷宫。

有些格子是小Hi可以经过的,我们用’.’表示;有些格子上有障碍物小Hi不能经过,我们用’#’表示。小Hi的起始位置用’S’表示,他需要到达用’T’表示的格子才能逃离迷宫。

麻烦的是小Hi被坏女巫施了魔法,他只能选择上下左右某一个方向,沿着这个方向一直走,直到遇到障碍物或者迷宫边界才能改变方向。新的方向可以是上下左右四个方向之一。之后他还是只能沿着新的方向一直走直到再次遇到障碍物或者迷宫边界……

小Hi想知道他最少改变几次方向才能逃离这个迷宫。
输入

第一行包含两个整数N和M。 (1 <= N, M <= 500)

以下N行每行M个字符,代表迷宫。
输出

一个整数代表答案。如果小Hi没法逃离迷宫,输出-1。
样例输入

5 5
S.#.T  
.....  
.....  
.....  
.....

样例输出

2

有个细节 坑了好多发, 没仔细看题, 题目说 直到遇到障碍物或着地图边界才允许转弯。。。。中途可不能瞎跑。


#include<iostream>
#include<sstream>
#include<algorithm>
#include<cstdio>
#include<string.h>
#include<cctype>
#include<string>
#include<cmath>
#include<vector>
#include<stack>
#include<queue>
#include<map>
#include<set>
using namespace std;
const int INF = 555;
char g[INF][INF];
int dir[][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
bool vis[INF][INF];
int n, m;

struct Node {
    int x, y;
    int step;
    Node(int xx, int yy, int s):x(xx), y(yy), step(s){};
    Node(){}
};

int bfs(Node s) {
    queue<Node> q;
    q.push(s);
    vis[s.x][s.y] = true;
    while(!q.empty()) {
        Node f = q.front();
        q.pop();
        int step = f.step + 1;
        for(int i = 0; i < 4; i++) {
            int tx = f.x + dir[i][0];
            int ty = f.y + dir[i][1];

            while(g[tx][ty] != '#' && tx >= 0 && tx < n && ty >= 0 && ty < m) {
                if(g[tx][ty] == 'T') {
                    return step;
                }
                tx = tx + dir[i][0];
                ty = ty + dir[i][1];
            }
            tx = tx - dir[i][0];
            ty = ty - dir[i][1];
            if(!vis[tx][ty]) {
                vis[tx][ty] = true;

                q.push(Node(tx, ty, step));
            }
        }
    }
    return -1;
}
int main() {
   while(scanf("%d%d", &n, &m) != EOF) {
    Node s;int flag = 0;
    memset(vis, false, sizeof(vis));
    memset(g, '\0', sizeof(g));
    for(int i = 0; i < n; i++) {
        scanf("%s", g[i]);

        for(int j = 0; j < m; j++) {
            if(g[i][j] == 'S') {
                s.x = i;
                s.y = j;
                flag = 1;
                s.step = -1;
            }

        }

    }
    if(!flag) {
        printf("-1\n");
        continue;
    }
     int res = bfs(s);
     printf("%d\n", res);
   }
   return 0;
}
/*


10 5
S#T#.
.#..#
.##..
.#.#.
.....
.##..
.#...
.###.
.#.#.
.....


10 5
S..#.
....#
.#.T.
.#T#.
.....
.##..
.#...
.###.
.#.#.
.....


4 5
S.#..
.#...
.###.
....T
5 5
T.#.S
...#.
.....
.....
.....
5 5
ST#..
.....
.....
.....
.....
1 2
ST
5 5
#S...
..#.#
.#...
...#.
..T..
5 5
#S...
..#.#
.#...
...#.
T....
5 5
#S...
..#.#
.#...
...#.
.....
2 2
S#
.T
*/
posted @ 2017-05-11 10:15  cbam  阅读(146)  评论(0)    收藏  举报