HDU 1175 (DFS+剪枝)
阿新 • • 發佈:2018-12-14
很有意思的一題哈……
(寫完了把每次錯的就改正了重新提交我可去你的吧=A=)
看完題目硬是想不出怎麼判斷轉了一個彎 紫書上也有轉彎的題但是感覺和這個不一樣……
剪枝和象棋那個題有點像很好理解
煩的是莫名其妙的WA(死在粗心打錯看不到)
內容很簡單很普通的DFS……細心點做……
#include <iostream> #include <string> #include <cstring> #include <sstream> #include <algorithm> #include <vector> #include <queue> #include <map> #include <cmath> using namespace std; int n, m; int mm[1005][1005]; int vis[1005][1005]; int mov[][2] = { 0,1,1,0,0,-1,-1,0 }; int flag; bool judge(int x, int y) { if (x<1 || x>n || y<1 || y>m) return false; return true; } void dfs(int x1, int y1, int x2, int y2, int dir, int turn) { if (flag || turn > 2)return; if (turn == 2 && x1 != x2 && y1 != y2)return; for (int i = 0; i < 4; i++) { int xx = x1 + mov[i][0]; int yy = y1 + mov[i][1]; if (xx == x2 && yy == y2) { flag = 1; return; } if (!judge(xx, yy) || mm[xx][yy] != 0 || vis[xx][yy] == 1)continue; vis[xx][yy] = 1; if (i == dir || dir == -1) dfs(xx, yy, x2, y2, i, turn); else dfs(xx, yy, x2, y2, i, turn + 1); vis[xx][yy] = 0; } } int main() { while (cin >> n >> m && n != 0 && m != 0) { for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) cin >> mm[i][j]; int q; cin >> q; while (q--) { memset(vis, 0, sizeof(vis)); flag = 0; int x1, y1, x2, y2; cin >> x1 >> y1 >> x2 >> y2; if (mm[x1][y1] != mm[x2][y2] || mm[x1][y1] == 0 || (x1 == x2 && y1 == y2) || !judge(x1, y1) || !judge(x2, y2)) { cout << "NO" << endl; continue; } dfs(x1, y1, x2, y2, -1, 0); if (flag) cout << "YES" << endl; else cout << "NO" << endl; } } system("pause"); return 0; }