3,881
社区成员
发帖
与我相关
我的任务
分享
#include<iostream>
using namespace std;
int sx,sy;
int ex,ey;
int n,m,T;
int i,j,k;
int flag;//是否成功标记
char maze[10][10];
int vis[10][10];
int d[4][2] = {{0,-1},{0,1},{-1,0},{1,0}};
//判断坐标(x,y)是否在界内
int IsRight(int x,int y)
{
if(0<=x && x<n && 0<=y && y<m)
return 1;
else return 0;
}
void dfs(int x,int y,int t)
{
if(!IsRight(x,y))//坐标不再界内
return;
if( x==ex && y==ey && t == T)
{
flag = 1;
cout << t << endl;
return;
}
for(i=0;i<4;i++)//从4个方向探测
{
int newx = x + d[i][0];
int newy = y + d[i][1];
if(IsRight(newx,newy))
{
if(maze[newx][newy]!='X' && vis[newx][newy]==0)
{
vis[newx][newy]=1;
dfs(newx,newy,t+1);
vis[newx][newy]=0;//回溯
}
}
}
}
int main()
{
freopen("in.txt","r",stdin);
while(1)
{
cin >> n >> m >> T;
if(n==0 && m==0 && T==0)
break;
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
vis[i][j] = 0;
cin >> maze[i][j];
if(maze[i][j]=='S')
sx=i , sy=j;
if(maze[i][j]=='D')
ex=i , ey=j;
}
}
int t = 0;
flag = 0;
dfs(sx,sy,t);
if(flag==1)
cout << "YES" << endl;
else
cout << "NO" << endl;
}
return 0;
}
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
char map[9][9];
int n,m,t,di,dj; //(di,dj):门的位置
bool escape;
int dir[4][2]={{0,-1},{0,1},{1,0},{-1,0}}; //分别表示下、上、左、右四个方向
void dfs(int si,int sj,int cnt) //表示起始位置为(si,sj),要求在第cnt秒达到门的位置
{
int i,temp;
if( si>n || sj>m || si<=0 || sj<=0 ) return;
if( si==di && sj==dj && cnt==t )
{
escape = 1;
return;
}
temp = (t-cnt) - abs(si-di) - abs(sj-dj);
if( temp<0 || temp&1 ) return;
for( i=0; i<4; i++ )
{
if( map[ si+dir[i][0] ][ sj+dir[i][1] ] != 'X')
{
map[ si+dir[i][0] ][ sj+dir[i][1] ] = 'X';
dfs(si+dir[i][0], sj+dir[i][1], cnt+1);
if(escape) return;
map[ si+dir[i][0] ][ sj+dir[i][1] ] = '.';
}
}
return;
}
int main()
{
int i,j,si,sj;
while( cin >> n >> m >> t)
{
if( n==0 && m==0 && t==0 )
break;
int wall = 0;
for( i=1; i<=n; i++ )
for( j=1; j<=m; j++ )
{
cin >> map[i][j];
if(map[i][j]=='S') { si=i; sj=j; }
else if( map[i][j]=='D' ) { di=i; dj=j; }
else if( map[i][j]=='X' ) wall++;
}
if( n*m-wall <= t )
{
cout << "NO" << endl;
continue;
}
escape = 0;
map[si][sj] = 'X';
dfs( si, sj, 0 );
if( escape ) cout << "YES" << endl;
else cout << "NO" << endl;
}
return 0;
}
[ Copy to Clipboard ] [ Save to File]
AC代码供参考