HDOJ 1010 Tempter of the Bone
思路:
DFS+回溯,单单这样会超时,需奇偶性剪枝,即|x2-x1|+|y2-y1|与步数的奇偶性相同,不相同直接输出"NO",相同再进行DFS
1 #include<iostream> 2 #include<cstring> 3 #include<cstdio> 4 #include<cstdlib> 5 6 #define REP(i,l,r) for(int i=(l);i<=(r);++i) 7 #define REP2(i,l,r) for(int i=(l);i>=(r);--i) 8 #define SCAN(n) scanf("%d",&n) 9 #define SCAN2(a,b) scanf("%d%d",&a,&b) 10 #define SCANS(s) scanf("%s",s) 11 #define PRINT(n) scanf("%d\n",n) 12 #define CLR(dp,a) memset(dp,a,sizeof(dp)) 13 14 using namespace std; 15 16 int vis[10][10]; 17 char maze[10][10]; 18 19 int x1,y1,x2,y2; 20 21 int dx[4]={-1,1,0,0}; 22 int dy[4]={0,0,1,-1}; 23 24 int n,m; 25 26 int dfs(int x,int y,int t){ 27 if(t==0&&x==x2&&y==y2) return 1; 28 if(t==0) return 0; 29 for(int i=0;i<4;i++){ 30 int fx=x+dx[i]; 31 int fy=y+dy[i]; 32 vis[x][y]=1; 33 if(!vis[fx][fy]&&fx>=0&&fx<n&&fx>=0&&fy<m&&maze[fx][fy]=='.') 34 if(dfs(fx,fy,t-1)) return 1; 35 vis[x][y]=0; 36 } 37 return 0; 38 } 39 40 int main(){ 41 int t; 42 while(scanf("%d %d %d",&n,&m,&t)!=EOF){ 43 if(!n&&!m&&!t) break; 44 CLR(vis,0); 45 REP(i,0,n-1){ 46 SCANS(maze[i]); 47 REP(j,0,m-1){ 48 if(maze[i][j]=='S') x1=i,y1=j; 49 if(maze[i][j]=='D'){ 50 x2=i,y2=j; 51 maze[i][j]='.'; 52 } 53 } 54 } 55 int j=abs(x2-x1)+abs(y2-y1); 56 if((j%2)!=(t%2)) printf("NO\n"); 57 else printf(dfs(x1,y1,t)?"YES\n":"NO\n"); 58 } 59 return 0; 60 }