1010

dfs精髓剪枝呀,长时间不做搜索,剪枝都忘了,7*7图的复杂度应该是4^49吧。

#include <iostream>
using namespace std;

char map[7][7];
bool mm[7][7];
int m,n,t;
int sx,sy;
int ex,ey;
int cnt;
bool ok;

int step[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
void dfs(int x,int y,int tt){
	if(tt>t) return;
	if(x<0||x>=n||y<0||y>=m) return;
	if(map[x][y]=='X') {mm[x][y]=1; return;}
	if(mm[x][y]) return;
	if(((x+y-ex-ey)%2+2)%2!=(t-tt)%2) return;
	mm[x][y]=1;
	if(map[x][y]=='D'&&tt==t) { ok=true;return;}
	for(int i=0; i<4; ++i){
		dfs(x+step[i][0],y+step[i][1],tt+1);
		if(ok) return;
	}
	mm[x][y]=0;
}
int main(){
	while(cin>>n>>m>>t){
		if(n==0)
			break;
		ok=false;
		cnt=0;
		memset(mm,0,sizeof(mm));
		for(int i=0; i<n; ++i)
			for(int j=0; j<m; ++j){
				cin>>map[i][j];
                if(map[i][j]=='S'){
                	sx=i;sy=j;
                }
                if(map[i][j]=='D'){
                	ex=i;ey=j;
                }
                if(map[i][j]=='X'){
                	++cnt;
                }
			}
		if(((sx+sy-ex-ey)%2+2)%2!=t%2)
			cout<<"NO"<<endl;
		//cout<<"OK"<<endl;
		else if(m*n-cnt<t)
			cout<<"NO"<<endl;
		else{
		dfs(sx,sy,0);
		if(ok)
			cout<<"YES"<<endl;
		else
			cout<<"NO"<<endl;
		}

	}
}

你可能感兴趣的:(1010)