from cmath import inf
from collections import deque
n, m = map(int, input().split())
grid = [[i for i in input()] for _ in range(n)]
directions = [(1,0),(0,1),(-1,0),(0,-1)]
def solve(n, m, grid):
for i in range(n):
for j in range(m):
if grid[i][j] == "S":
start = (i, j)
queue = deque()
for dr, dc in directions:
queue.append(((start, (dr, dc), 0)))
visited = [[inf for _ in range(m)] for _ in range(n)]
while queue:
pos, dir, turns = queue.popleft()
if grid[pos[0]][pos[1]] == "T" and turns <= 2:
return True
if turns > 2:
continue
for dr, dc in directions:
nr, nc = pos[0] + dr, pos[1] + dc
if 0<=nr<n and 0<=nc<m and grid[nr][nc] != "*" and visited[nr][nc] >= turns+1:
if dir == (dr, dc):
queue.append(((nr, nc), (dr, dc), turns))
visited[nr][nc] = turns
elif turns < 2:
queue.append(((nr, nc), (dr, dc), turns + 1))
visited[nr][nc] = turns + 1
return False
if solve(n, m, grid):
print("YES")
else:
print("NO")
#include <bits/stdc++.h>
using namespace std;
int n, m,sx,sy,ex,ey;
vector<vector<char>> a;
bool f;
bool vst[1002][1002][4][26];
bool valid(int i,int j){return i>0&&j>0&&i<=n&&j<=m&&a[i][j]!='*';}
void dfs(int i=sx,int j=sy,int turn=-1,char last='X'){
// cout <<i<<' '<<j<<' '<<turn<<'\n';
if (turn >2||vst[i][j][turn][last-'A'])return;
if (i==ex&&j==ey){
f=1;
return ;
}
vst[i][j][turn][last-'A']=1;
if (valid(i+1,j))dfs(i+1,j,turn +(last!='D'),'D');
if (valid(i-1,j))dfs(i-1,j,turn +(last!='U'),'U');
if (valid(i,j+1))dfs(i,j+1,turn +(last!='R'),'R');
if (valid(i,j-1))dfs(i,j-1,turn +(last!='L'),'L');
}
int main() {
cin >> n >> m;
a.resize(n + 2, vector<char>(m + 2));
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) {
cin >> a[i][j];
if (a[i][j]=='S')sx=i,sy=j;
if (a[i][j]=='T')ex=i,ey=j;
}
dfs(sx,sy,-1,'X');
cout <<(f?"YES":"NO");
}
543. Diameter of Binary Tree | 124. Binary Tree Maximum Path Sum |
1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts | 501A - Contest |
160A- Twins | 752. Open the Lock |
1535A - Fair Playoff | 1538F - Interesting Function |
1920. Build Array from Permutation | 494. Target Sum |
797. All Paths From Source to Target | 1547B - Alphabetical Strings |
1550A - Find The Array | 118B - Present from Lena |
27A - Next Test | 785. Is Graph Bipartite |
90. Subsets II | 1560A - Dislike of Threes |
36. Valid Sudoku | 557. Reverse Words in a String III |
566. Reshape the Matrix | 167. Two Sum II - Input array is sorted |
387. First Unique Character in a String | 383. Ransom Note |
242. Valid Anagram | 141. Linked List Cycle |
21. Merge Two Sorted Lists | 203. Remove Linked List Elements |
733. Flood Fill | 206. Reverse Linked List |