Codeforces Round #442 (Div. 2) 877 D. Olya and Energy Drinks BFS
2017-10-25 23:40
381 查看
题目链接: D. Olya and Energy Drinks
题目大意
一个n*m的迷宫, 0≤m,n≤103, 给定一个起点和一个终点, 每秒可以向上下左右中的某一个方向最多前进k步, 求起点到终点最少需要花费的时间思路
最普通的BFS, 但复杂度O(nmk)=109, 会超时, 但是只要遇到终点立即退出(输出答案然后return), 就能过代码
GNU C++14 Accepted 1747 ms 13600 KB#include <iostream> #include <algorithm> #include <cstring> #include <cstdio> #include <queue> using namespace std; const int maxn = 1e3 + 10; int n, m, k, d[maxn][maxn]; int x_1, x_2, y_1, y_2; int dx[] = {0, 0, 1, -1}; int dy[] = {1, -1, 0, 0}; char s[maxn][maxn]; typedef pair<int, int> P; int main() { scanf("%d%d%d", &n, &m, &k); for (int i = 0; i < n; ++i) scanf("%s", s[i]); scanf("%d%d%d%d", &x_1, &y_1, &x_2, &y_2); if(x_1 == x_2 && y_1 == y_2) { cout << 0 << endl; return 0; } --x_1, --x_2, --y_1, --y_2; memset(d, -1, sizeof(d)); d[x_1][y_1] = 0; queue<P> que; que.push(P(x_1, y_1)); while (!que.empty()) { P now = que.front(); que.pop(); for (int i = 0; i < 4; ++i) { for (int a = 1; a <= k; ++a) { int nx = now.first + dx[i] * a; int ny = now.second + dy[i] * a; if (0 <= nx && nx < n && 0 <= ny && ny < m && d[nx][ny] == -1 && s[nx][ny] == '.') { d[nx][ny] = d[now.first][now.second] + 1; que.push(P(nx, ny)); if (nx == x_2 && ny == y_2) { cout << d[x_2][y_2] << endl; return 0; } } else if (nx < 0 || nx >= n || ny < 0 || ny >= m || s[nx][ny] == '#') break; } } } cout << -1 << endl; return 0; }
相关文章推荐
- Codeforces Round #442 (Div. 2) D. Olya and Energy Drinks (bfs)
- Codeforces Round #442 (Div. 2) Olya and Energy Drinks(搜索 bfs 套路题)
- codeforces 877 problem D Olya and Energy Drinks 【bfs剪枝】
- Codeforces 877 D. Olya and Energy Drinks (bfs)
- Codeforces Round #442(Div.2)Problem D Olya and Energy Drinks(BFS)
- Codeforces Round #442 (Div. 2)-广搜&剪枝&技巧&好题-D. Olya and Energy Drinks
- codeforces #442 div2 Olya and Energy Drinks
- Codeforces 877 D. Olya and Energy Drinks
- Codeforces Round #442 (Div. 2) D. Olya and Energy Drinks
- Codeforces Round #877 (Div. 2) D. Olya and Energy Drinks
- Codeforces 877 D Olya and Energy Drinks
- 【Codeforces Round #442 (Div. 2) D】Olya and Energy Drinks
- cf 442 D. Olya and Energy Drinks
- Codeforces Round #179 (Div. 1) C. Greg and Friends(BFS 或者最短路)
- Codeforces Round #416 (Div. 2) D. Vladik and Favorite Game【交互题+BFS】
- 【分类讨论】【spfa】【BFS】Codeforces Round #416 (Div. 2) D. Vladik and Favorite Game
- Codeforces Round #361 (Div. 2)B. Mike and Shortcuts【BFS】
- Codeforces Round #297 (Div. 2)D. Arthur and Walls 搜索bfs
- IndiaHacks 2016 - Online Edition (Div. 1 + Div. 2) E. Bear and Forgotten Tree 2 bfs set 反图的生成树★ ★
- 【Codeforces Round 354 (Div 2)D】【迷宫搜索BFS】Theseus and labyrinth 门门互达 可做旋转操作 最少步数起点到终点