标签:
题目链接:http://acm.split.hdu.edu.cn/showproblem.php?pid=1175
越学越不会,BFS还是很高级的。
Time Limit: 20000/10000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 30994 Accepted Submission(s): 7694
#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <algorithm> #include <iostream> #include <queue> using namespace std; const int MAXN = 1010; int maps[MAXN][MAXN]; bool visited[MAXN][MAXN][4]; int M, N; const int to[4][2] = { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } }; struct Node { int x, y; int dire, turn; }; void init() { for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) { scanf("%d", &maps[i][j]); } } } bool BFS(int x1, int y1, int x2, int y2) { memset(visited, false, sizeof(visited)); queue<Node> que; Node s; s.x = x1; s.y = y1; s.dire = -1; s.turn = -1; que.push(s); for (int i = 0; i < 4; i++) visited[x1][y1][i] = true; while (!que.empty()) { Node u = que.front(); que.pop(); if (u.turn > 2) continue; for (int j = 0; j < 4; j++) { Node next; next.turn = u.turn; if (u.dire != j) { next.turn++; } for (int k = 1;; k++) { next.x = u.x + to[j][0] * k; next.y = u.y + to[j][1] * k; if (next.x <= 0 || next.y <= 0 || next.x > N || next.y > M) break; if (next.x == x2 && next.y == y2) { if (next.turn <= 2) { return true; } } if (maps[next.x][next.y] > 0 || visited[next.x][next.y][j]) { break; } next.dire = j; que.push(next); visited[next.x][next.y][j] = true; } } } return false; } int main() { //freopen("input.txt", "r", stdin); int Q, x1, y1, x2, y2; while (scanf("%d%d", &N, &M) == 2) { if (N == 0 && M == 0) { break; } init(); scanf("%d", &Q); for (int i = 0; i < Q; i++) { scanf("%d%d%d%d", &x1, &y1, &x2, &y2); if (!maps[x1][y1] || !maps[x2][y2] || maps[x1][y1] != maps[x2][y2]) { puts("NO"); continue; } if (BFS(x1, y1, x2, y2)) { puts("YES"); } else { puts("NO"); } } } return 0; }
标签:
原文地址:http://www.cnblogs.com/TreeDream/p/5792829.html