标签:process hat Once min des short other void lock
InputThe input consists of multiple test cases. The first line of each test case contains three integers N, M, and T (1 < N, M < 7; 0 < T < 50), which denote the sizes of the maze and the time at which the door will open, respectively. The next N lines give the maze layout, with each line containing M characters. A character is one of the following:
‘X‘: a block of wall, which the doggie cannot enter;
‘S‘: the start point of the doggie;
‘D‘: the Door; or
‘.‘: an empty block.
The input is terminated with three 0‘s. This test case is not to be processed.
OutputFor each test case, print in one line "YES" if the doggie can survive, or "NO" otherwise.
Sample Input
4 4 5 S.X. ..X. ..XD .... 3 4 5 S.X. ..X. ...D 0 0 0
Sample Output
NO YES
分析:做的时候以为很简单,然后一直超时,才知道要进行奇偶剪枝,题目要求T步从起点到达终点,设起点S(sx, sy),终点E(ex, ey),那么S到E的最短路长度为L = abs(ex - sx) + abs(ey - sy),那么所有从S到E的路径都和L同奇同偶,(不理解的好好想想),而且L必须要小于等于T才可能到达终点,那么就可以利用这两个性质来进行剪枝
int flag = t - num - abs(x - ex) - abs(y - ey);
if(flag < 0 || flag&1) return;
代码:
#include<iostream> #include<cstdio> #include<cmath> using namespace std; const int N = 10; char mp[N][N]; int dx[4] = {0, 0, 1, -1}; int dy[4] = {1, -1, 0, 0}; int n, m, t; int sx, sy, ex, ey; int ok; int check(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; } void dfs(int x, int y, int num) { if(x == ex && y == ey && num == t) ok = 1; if(ok == 1) return; int flag = t - num - abs(x - ex) - abs(y - ey); if(flag < 0 || flag&1) return; for(int i = 0; i < 4; i++) { int nx = x + dx[i], ny = y + dy[i]; if(check(nx, ny) && mp[nx][ny] != ‘X‘) { mp[nx][ny] = ‘X‘; dfs(nx, ny, num + 1); mp[nx][ny] = ‘.‘; } } } int main() { while(scanf("%d%d%d", &n, &m, &t) == 3 && n && m && t) { for(int i = 0; i < n; i++) { scanf("%s", mp[i]); for(int j = 0; j < m; j++) { if(mp[i][j] == ‘S‘) { sx = i; sy = j; } if(mp[i][j] == ‘D‘) { ex = i; ey = j; } } } mp[sx][sy] = ‘X‘; int flag = t - abs(sx - ex) - abs(sy - ey); if(flag < 0 || flag&1) { printf("NO\n"); continue; } ok = 0; dfs(sx, sy, 0); if(ok) printf("YES\n"); else printf("NO\n"); } return 0; }
标签:process hat Once min des short other void lock
原文地址:https://www.cnblogs.com/kindleheart/p/9297333.html