2014_3_29_周赛 着火的最短路

来源:互联网 发布:网络推广员怎么做 编辑:程序博客网 时间:2024/04/28 12:12
题目描述

一个 n*m 的网格里有一些点着火了,火在每单位时间向八连通的相邻点蔓延。Alice 欲从点 S(x_s, y_s) 在最短时间内到达点T(x_t, y_t),她在每单位时间只能移动至四连通的相邻点。已经着火的点不能进入。 S 与 T 在时间零点上不着火。


输入格式

输入包含多组数据,以 EOF 结束。

对于每组数据,第一行包含两个整数 m,n。接下来 m 行给出一个字符矩阵,其中 . 表示普通的点,F 表示在时间零点上着火的点,S 表示 Alice 的起点,T 表示 Alice 的终点。其中 S 与 T 各只出现一次。

0 < n, m <= 100

输出

若 Alice 能活着到达终点,输出她所用时间;若她不能穿过火焰到达终点,输出 -1。
样例输入

8 10
..........
.F........
..........
..........
..........
....S.....
.........T
..........
6 10
..........
..........
.S........
..........
.........T
...FF.....
样例输出

6
-1
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <queue>using namespace std;typedef struct node {    int x, y, step;} node;const int dx[4] = {1, 0, -1, 0};const int dy[4] = {0, 1, 0, -1};char a[105][105];bool vis[105][105];int F[10005][2];int m, n, sx, sy, tx, ty, numf;bool check(int x, int y, int t) {    if (x < 0 || x >= m || y < 0 || y >= n)        return false;    if (a[x][y] == 'F')        return false;    for (int i = 0; i < numf; i++) {        if (abs(x - F[i][0]) <= t && abs(y - F[i][1]) <= t)//就是这一个括号的位置错了,第一次WA了            return false;    }    return true;}int bfs() {    memset(vis, 0, sizeof (vis));    queue<node> q;    node h, n;    h.x = sx;    h.y = sy;    h.step = 0;    q.push(h);    while (!q.empty()) {        h = q.front();        q.pop();        if (h.x == tx && h.y == ty)            return h.step;        for (int i = 0; i < 4; i++) {            n.x = h.x + dx[i];            n.y = h.y + dy[i];            n.step = h.step + 1;            if (check(n.x, n.y, n.step) && !vis[n.x][n.y]) {                q.push(n);                vis[n.x][n.y] = true;            }        }    }    return -1;}int main() {    while (scanf("%d%d", &m, &n) == 2) {        numf = 0;        for (int i = 0; i < m; i++)            scanf("%s", a[i]);        for (int i = 0; i < m; i++)            for (int j = 0; j < n; j++) {                if (a[i][j] == 'S') {                    sx = i;                    sy = j;                }                if (a[i][j] == 'T') {                    tx = i;                    ty = j;                }                if (a[i][j] == 'F') {                    F[numf][0] = i;                    F[numf][1] = j;                    numf++;                }            }        printf("%d\n", bfs());    }    return 0;}


0 0