[Usaco2008 Mar]Cow Travelling游荡的奶牛 BFS

奶牛们在被划分成N行M列(2 <= N <= 100; 2 <= M <= 100)的草地上游走, 试图找到整块草地中最美味的牧草。Farmer John在某个时刻看见贝茜在位置 (R1, C1),恰好T (0 < T <= 15)秒后,FJ又在位置(R2, C2)与贝茜撞了正着。 FJ并不知道在这T秒内贝茜是否曾经到过(R2, C2),他能确定的只是,现在贝茜 在那里。 设S为奶牛在T秒内从(R1, C1)走到(R2, C2)所能选择的路径总数,FJ希望有 一个程序来帮他计算这个值。每一秒内,奶牛会水平或垂直地移动1单位距离( 奶牛总是在移动,不会在某秒内停在它上一秒所在的点)。草地上的某些地方有 树,自然,奶牛不能走到树所在的位置,也不会走出草地。 现在你拿到了一张整块草地的地形图,其中'.'表示平坦的草地,'*'表示 挡路的树。你的任务是计算出,一头在T秒内从(R1, C1)移动到(R2, C2)的奶牛 可能经过的路径有哪些。



这题呢,第一想法就是直接搜索了。

至于用什么搜索,我偏向于用bfs来搜索。

用dp[i, j, k]表示到达(i, j)这个点用时为 k的路径数

然后每次他能从四周的点 用时为k - 1的状态转移过来。


#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
int dp[111][111][18];
int vis[111][111][18];
int xx[] = {0, 1, 0, -1};
int yy[] = {1, 0, -1, 0};
int T;
struct P
{
    int x, y, num;
    P(){}
    P(int _x, int _y, int _num){ x = _x; y = _y; num = _num;}
};
queue<P>q;
int sx, sy, ex, ey, n, m;
char s[111][111];
bool inside(int x, int y)
{
    if(x < 0 || x >= n || y < 0 || y >= m || s[x][y] == '*') return false;
    return true;
}
void bfs()
{
    q.push(P(sx, sy, 0));
    vis[sx][sy][0] = 1;
    dp[sx][sy][0] = 1;
    while(!q.empty())
    {
        P tmp = q.front();
        q.pop();
        if(tmp.num > T) break;
        for(int i = 0; i < 4; i++)
        {
            int tx = xx[i] + tmp.x;
            int ty = yy[i] + tmp.y;
            if(inside(tx, ty))
            {
                dp[tx][ty][tmp.num + 1] += dp[tmp.x][tmp.y][tmp.num];
                if(!vis[tx][ty][tmp.num + 1])
                {
                    q.push(P(tx, ty, tmp.num + 1));
                    vis[tx][ty][tmp.num + 1] = 1;
                }
            }
        }
    }
    printf("%d\n", dp[ex][ey][T]);
}
int main()
{
    scanf("%d%d%d", &n, &m, &T);
    for(int i = 0; i < n; i++) scanf("%s", s[i]);
    scanf("%d%d%d%d", &sx, &sy, &ex, &ey);
    sx--; sy--; ex--; ey--;
    bfs();
    return 0;
}


你可能感兴趣的:([Usaco2008 Mar]Cow Travelling游荡的奶牛 BFS)