D. Olya and Energy Drinks
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
Olya loves energy drinks. She loves them so much that her room is full of empty cans from energy drinks.
Formally, her room can be represented as a field of n × m cells, each cell of which is empty or littered with cans.
Olya drank a lot of energy drink, so now she can run k meters per second. Each second she chooses one of the four directions (up, down, left or right) and runs from 1 to k meters in this direction. Of course, she can only run through empty cells.
Now Olya needs to get from cell (x1, y1) to cell (x2, y2). How many seconds will it take her if she moves optimally?
It’s guaranteed that cells (x1, y1) and (x2, y2) are empty. These cells can coincide.
Input
The first line contains three integers n, m and k (1 ≤ n, m, k ≤ 1000) — the sizes of the room and Olya’s speed.
Then n lines follow containing m characters each, the i-th of them contains on j-th position “#”, if the cell (i, j) is littered with cans, and “.” otherwise.
The last line contains four integers x1, y1, x2, y2 (1 ≤ x1, x2 ≤ n, 1 ≤ y1, y2 ≤ m) — the coordinates of the first and the last cells.
Output
Print a single integer — the minimum time it will take Olya to get from (x1, y1) to (x2, y2).
If it’s impossible to get from (x1, y1) to (x2, y2), print -1.
Examples
input
3 4 4
….
….
1 1 3 1
output
3
input
3 4 1
….
….
1 1 3 1
output
8
input
2 2 1
.#
1 1 2 2
output
-1
有一个图,每次可以向一个方向走1-k步,问最小需要多少不可以到到终点。
看到了一个直接bfs的做法,最开始以为是n^3的做法,细细看了下,是n^2的。
#include
#include
#include
#include
#include
#include
using namespace std;
const int maxn = 1000;
int rowmod[4] = { 0,1,0,-1 };
int colmod[4] = { 1,0,-1,0 };
int n, m, k;
int x1, x2, ys, y2;
char G[maxn][maxn];
bool vis[maxn][maxn];
int step[maxn][maxn];
queueint ,int> > q;
void bfs() {
step[x1][ys] = 0;
q.push(make_pair(x1,ys));
while (!q.empty()) {
int r = q.front().first;
int c = q.front().second;
q.pop();
if (vis[r][c])continue;
else vis[r][c] = true;
for (int i = 0; i < 4; i++) {
for (int j = 1; j <= k; j++) {
int nr = r + rowmod[i] * j;
int nc = c + colmod[i] * j;
if (G[nr][nc] == '#'||nr<0||nr>=n||nc<0||nc>=m)break;
/*-----------------------------------------------------*/
if (step[nr][nc] != -1 && step[nr][nc] < step[r][c] + 1)break;
if (!vis[nr][nc])q.push(make_pair(nr,nc));
step[nr][nc] = step[r][c] + 1;
}
}
}
}
int main() {
cin >> n >> m >> k;
for (int i = 0; i < n; i++) scanf("%s", G[i]);
scanf("%d%d%d%d", &x1, &ys, &x2, &y2);
memset(vis, false, sizeof(vis));
x1 -= 1; ys -= 1; x2 -= 1; y2 -= 1;
memset(step, -1, sizeof(step));
bfs();
cout << step[x2][y2] << endl;
return 0;
}
这大概就是剪枝的力量吧。