Description
奶牛們在被劃分成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)的奶牛可能經過的路徑有哪些。
Input
第1行: 3個用空格隔開的整數:N,M,T
第2..N+1行: 第i+1行爲M個連續的字符,描述了草地第i行各點的情況,保證 字符是’.’和’‘中的一個 第N+2行: 4個用空格隔開的整數:R1,C1,R2,以及C2
Output
第1行: 輸出S,含義如題中所述
Sample Input
4 5 6
…*.
…*.
…..
…..
1 3 1 5
輸入說明:
草地被劃分成4行5列,奶牛在6秒內從第1行第3列走到了第1行第5列。
Sample Output
1
奶牛在6秒內從(1,3)走到(1,5)的方法只有一種(繞過她面前的樹)。
Solution
是時候刷一波權限題了。
記
有一個剪枝,設當前步數爲step,如果當前座標到終點的曼哈頓距離大於
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>
#include <cmath>
using namespace std;
int n, m, T;
char map[105][105];
int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int sx, sy, ex, ey;
struct Node{
int x, y, step;
Node() {}
Node(int a, int b, int c) : x(a), y(b), step(c) {}
};
bool check(int x, int y, int step) {
if (x < 0 || x >= n || y < 0 || y >= m) return false;
if (map[x][y] == '*') return false;
if (abs(ex - x) + abs(ey - y) > T - step) return false;
return true;
}
int tot[105][105][18];
bool vis[105][105][18];
int bfs() {
queue<Node> q;
tot[sx][sy][0] = 1;
vis[sx][sy][0] = 1;
q.push(Node(sx, sy, 0));
while (!q.empty()) {
Node cur = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
int nx = cur.x + dir[i][0];
int ny = cur.y + dir[i][1];
if (check(nx, ny, cur.step + 1)) {
tot[nx][ny][cur.step + 1] += tot[cur.x][cur.y][cur.step];
if (cur.step + 1 < T && !vis[nx][ny][cur.step + 1]) {
vis[nx][ny][cur.step + 1] = 1;
q.push(Node(nx, ny, cur.step + 1));
}
}
}
vis[cur.x][cur.y][cur.step] = 0;
}
return tot[ex][ey][T];
}
int main() {
scanf("%d %d %d", &n, &m, &T);
for (int i = 0; i < n; i++)
scanf("%s", map[i]);
scanf("%d %d %d %d", &sx, &sy, &ex, &ey);
sx--, sy--, ex--, ey--;
int res = bfs();
printf("%d\n", res);
return 0;
}