题意:在迷宫里,'X'表示墙,'S'表示起点,'D'表示终点,'.' 表示路,在起点处有一条狗,每秒可以移动一格,多组数据,每组第一行有三个数据,分别为迷宫的宽度和高度,与时间,判断这条狗是否能走出迷宫。
链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=1110
思路:因为迷宫范围比较小,可以用DFS搜索,因为要时间恰好为t秒,因此要用回溯法判断是否能在t秒是恰好到达'D'位置。
注意点:因为需时间恰好为t,因此需要在到达'D'位置时判断时间。
以下为AC代码:
Run ID | Submit Time | Judge Status | Problem ID | Language | Run Time(ms) | Run Memory(KB) | User Name |
3778570 | 2014-09-22 20:40:31 | Accepted | 2110 | C++0x | 200 | 272 | luminus |
#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <cstdio>
#include <cmath>
using namespace std;
struct node
{
int x;
int y;
};
bool flag;
struct node be;
struct node en;
int m, n, t;
char map[10][10];
int dir[4][2] = { 1, 0, -1, 0, 0, 1, 0, -1 };
void dfs ( int x, int y, int time )
{
if ( x == en.x && y == en.y )
{
if ( t == time )
{
flag = true;
return;
}
else
{
return;
}
}
for ( int i = 0; i < 4; i ++ )
{
map[x][y] = 'X';
if ( map[x + dir[i][0]][y + dir[i][1]] == '.' )
{
dfs ( x + dir[i][0], y + dir[i][1], time + 1 );
if ( flag )
{
return;
}
}
map[x][y] = '.';
}
}
bool judge ( int t )
{
int xi = abs ( be.x - en.x );
int yi = abs ( be.y - en.y );
if ( ( xi + yi ) % 2 == t % 2 )
{
return true;
}
else
{
return false;
}
}
int main()
{
while ( cin >> m >> n >> t )
{
if ( ! m && ! n && ! t )
{
return 0;
}
memset ( map, 'X', sizeof ( map ) );
flag = false;
cin.ignore();
for ( int i = 1; i <= m; i ++ )
{
for ( int j = 1; j <= n; j ++ )
{
cin >> map[i][j];
if ( map[i][j] == 'S')
{
be.x = i;
be.y = j;
map[i][j] = 'X';
}
else if ( map[i][j] == 'D' )
{
en.x = i;
en.y = j;
map[i][j] = '.';
}
}
}
if ( judge ( t ) )
{
dfs ( be.x, be.y, 0 );
}
if ( flag )
{
cout << "YES" << endl;
}
else
{
cout << "NO" << endl;
}
}
return 0;
}