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 5S.X...X...XD....3 4 5S.X...X....D0 0 0
Sample Output
NOYES 题意: 题意可以理解为从起点到终点恰好只经过T步路。 题解: 刚开始想到用BFS来做,代码写了写,改了改,然后答案就是不对。BFS适合用来求解最短路,但是对于这种题,规定只经过T步路到达终点,这时候BFS就无能为力了。 DFS搜索,注意回溯。还要剪枝,根据步数的奇偶性。起点到终点的步数和时间T同为奇数或偶数时,代表可能有解,否则,一定不可能在T时间准确到达终点。(具体可以手画一下坐标系)
#include#include #include #include using namespace std;char maze[10][10];bool flag;int n,m,ex,ey,cnt,t;int dx[4]={-1,0,1,0},dy[4]={ 0,-1,0,1};void dfs(int x,int y,int s){ if(x==ex&&y==ey&&s==t) { flag=true; return ; } if(abs(x-ex)+abs(y-ey)+s>t)//如果目前最短到终点的距离大于T就回溯 return ; if((t-s-abs(x-ex)-abs(y-ey))&1)//根据步数的奇偶性判断,差值为奇数就一定不能在T秒到达终点 return ; for(int i=0;i<4;i++) { int nx=x+dx[i],ny=y+dy[i]; if(0<=nx&&nx <=ny&&ny >n>>m>>t,n||m||t) { cnt=0; int sx,sy; for(int i=0;i >maze[i][j]; if(maze[i][j]=='S') { sx=i; sy=j; } if(maze[i][j]=='D') { ex=i; ey=j; } if(maze[i][j]=='X') cnt++; } flag=false; if(n*m-cnt