CodeForces - 793B Igor and his way to work dfs搜索

B. Igor and his way to work
time limit per test
3 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.

Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him.

Input

The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid.

Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur:

  • "." — an empty cell;
  • "*" — a cell with road works;
  • "S" — the cell where Igor's home is located;
  • "T" — the cell where Igor's office is located.

It is guaranteed that "S" and "T" appear exactly once each.

Output

In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise.

Examples
input
5 5
..S..
****.
T....
****.
.....
output
YES
input
5 5
S....
****.
.....
.****
..T..
output
NO
Note

The first sample is shown on the following picture:

CodeForces - 793B Igor and his way to work dfs搜索_第1张图片

In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture:

CodeForces - 793B Igor and his way to work dfs搜索_第2张图片
题意:一张图,从起点到终点,判断能不能在两次转弯内到达。

思路:蛮有技巧的一个dfs。

#include
#define N 1010
char maps[N][N];
int judge[N][N][2][3];
int n,m,flag;
int sx,sy;
void dfs(int x,int y,int d,int t)
{
    if(maps[x][y]=='T')
    {
        flag=1;
        return;
    }
    if(x<0||x>=n||y<0||y>=m)
        return;
    if(maps[x][y]=='*'||judge[x][y][d][t]||t>2||flag)
        return;
    judge[x][y][d][t]=1;//标记这个点是否走过,另加上了方向和转弯次数
    if(!d)
    {
        dfs(x+1,y,d,t);
        dfs(x-1,y,d,t);
    }
    else
    {
        dfs(x,y+1,d,t);
        dfs(x,y-1,d,t);
    }
    dfs(x,y,!d,t+1);//转向
}
int main()
{
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        int i,j;
        for(i=0;i

你可能感兴趣的:(简单算法,日常,简单搜索)