#include<iostream>
#include<cmath>
using namespace std;
int sx,sy,ex,ey;
int maze[10][10];
char maze_in[10];
int n,m,t;
bool sol;
int wall;
int dir[4][2]= {{1,0},{-1,0},{0,1},{0,-1}};
void dfs(int x, int y, int k)
{
if(k > t || sol == true)
return;
if(k == t && x == ex && y == ey){
sol = true;
return;
}
int tmp = t-k-abs(x-ex)-abs(y-ey);
if(tmp < 0 || (tmp %2 == 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<n && yy >= 0&&y < m&&maze[xx][yy] == 1){
maze[xx][yy] = 0;
dfs(xx,yy,k+1);
maze[xx][yy] = 1;
}
}
}
int main()
{
while(scanf("%d%d%d",&n,&m,&t) && n){
sol = false;
wall = 0;
for(int i = 0; i < n; i++ ){
scanf("%s",maze_in);
for(int j = 0; j < m; j++ ){
if(maze_in[j] == 'X'){
maze[i][j] = 0;
wall++;
}
else{
maze[i][j] = 1;
if(maze_in[j] == 'S'){
maze[i][j] = 0;
sx = i;
sy = j;
}
if(maze_in[j] == 'D'){
ex = i;
ey = j;
}
}
}
}
if(n*m-wall <= t || (abs(sx-ex)+abs(sy-ey) - t)%2 == 1 ){
cout << "NO\n";
continue;
}
dfs(sx,sy,0);
if(sol) cout<<"YES\n";
else
cout<<"NO\n";
}
return 0;
}
2、注意读取的时候直接找到S, D速度更快
#include<iostream>
#include<cstring>
#include<string>
#include<cmath>
using namespace std;
char map[10][10];
char maze[10];
int n, m, t;
int vis[10][10];
int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
int flag = 0;
int sX,sY,dX,dY;
int wal = 0;
void dfs(int x, int y, int s)
{
if(flag == 1 || s > t)
return;
if(map[x][y] == 'D' && s == t){
flag = 1;
return;
}
int tmp = t-s-abs(x-dX)-abs(y-dY);
if(tmp < 0 || tmp %2 == 1){
return;
}
for(int i = 0; i < 4; i++ ){
int xx = x+dir[i][0];
int yy = y+dir[i][1];
if(xx >= 0&&yy>=0&&xx<n&&yy<m && vis[xx][yy] == 0 && (map[xx][yy] =='.' || map[xx][yy] == 'D')){
vis[xx][yy] = 1;
dfs(xx,yy,s+1);
vis[xx][yy] = 0;
}
}
}
int main()
{
// freopen("C:\\Users\\zhangwei\\Desktop\\in.txt","w",stdout);
while(scanf("%d%d%d",&n,&m,&t) == 3 && m!=0 && n!=0 && t != 0){
memset(vis, 0, sizeof(vis));
wal = 0;
for(int i = 0; i < n; i++ ){
scanf("%s",maze);
for(int j = 0; j < m; j++ ){
if(maze[j] == '.')
map[i][j] = '.';
else if(maze[j] == 'X'){
map[i][j] = 'X';
wal++;
}
else{
if(maze[j] == 'S'){
map[i][j] = 'S';
sX = i;
sY = j;
vis[i][j] = 1;
}
if(maze[j]== 'D'){
map[i][j] = 'D';
dX = i;
dY = j;
}
}
}
}
if((n*m-wal) <= t || abs(sX-dX)+abs(sY-dY) > t || (t-abs(sX-dX)-abs(sY-dY)) % 2 == 1){
cout <<"NO\n";
continue;
}
flag = 0;
dfs(sX, sY, 0);
if(flag)
cout << "YES\n";
else
cout << "NO\n";
}
return 0;
}