标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 107138 Accepted Submission(s): 29131
题目大意是要在那个时间点找到D点,典型的DFS问题,重点是要求奇偶减枝
#include <stdio.h> #include <math.h> #include <cmath> #include <iostream> using namespace std; #define Maxn 100 int hang,lie,Time; char MAP[Maxn][Maxn]; int begin_x,begin_y; int end_x,end_y; bool flag; int dir[4][2] = { {0,1}, {0,-1}, {1,0}, {-1,0} }; void print() { for(int i = 0; i < hang; i++) { for(int j = 0; j < lie; j++) { printf("%c",MAP[i][j]); } printf("\n"); } } void dfs(int x, int y, int t) { // print(); // printf("\n"); if (flag) { return ; } // printf("Q\n", ); if (x == end_x && y == end_y && t == Time) { // printf("YES~~~~~~~~~~~\n"); flag = true; return ; } int temp = (Time - t) - ( abs(x- end_x) + abs(y - end_y) ); if (temp < 0 || temp & 1) { return ; // 奇偶剪枝 /*要理解奇偶剪枝,先了解一下曼哈顿距离, 从一个点到达另外一个点的最 短路径长度(时间)可以根据两点坐标求出, 路径长度(非最短)与最短路径的长度同奇偶, 它们的差一定是偶数!举个例子,就像两个偶数的差 差是偶数,两个个数的差也是偶数.*/ } for(int i = 0; i < 4; i++) { int xx = x + dir[i][0]; int yy = y + dir[i][1]; if (xx >= 0 && xx < hang && yy >= 0 && yy < lie) { if (MAP[xx][yy] != ‘X‘) { MAP[xx][yy] = ‘X‘; dfs(xx,yy,t+1); MAP[xx][yy] = ‘.‘; } } } return ; } int main() { while(cin >> hang >> lie >> Time,hang + lie + Time) { flag = false; for(int i = 0; i < hang; i++) { scanf("%s",MAP[i]); } for(int i = 0; i < hang; i++) { for(int j = 0; j < lie; j++) { if (MAP[i][j] == ‘S‘) { begin_x = i; begin_y = j; } else if (MAP[i][j] == ‘D‘) { end_x = i; end_y = j; } } } // printf("%d %d\n",begin_x,begin_y); MAP[begin_x][begin_y] = ‘X‘; dfs(begin_x,begin_y,0); if (flag) { printf("YES\n"); } else { printf("NO\n"); } } }
标签:
原文地址:http://www.cnblogs.com/yakoazz/p/5723292.html