深搜即可。
#include <bits/stdc++.h> using namespace std; const int maxn = 500+10; char a[maxn][maxn]; int begin_x, begin_y; int end_x, end_y; int n, m; bool vis[maxn][maxn]; bool flag = false; //对于上下左右的移动提前打表 int mv[4][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} }; void dfs(int x, int y) { vis[x][y] = true; if (x>n||y>m||x<=0||y<=0) return ; if (x==end_x&&y==end_y) { flag=true; return ; } //进行上下左右的移动 for (int i=0;i<4;i++) { int next_x = x+mv[i][0]; int next_y = y+mv[i][1]; if (!vis[next_x][next_y]&&a[next_x][next_y]!='x') { dfs(next_x, next_y); } } } int main() { int T; scanf("%d", &T); while (T--) { flag = false; memset(vis, 0, sizeof(vis)); scanf("%d %d ", &n, &m); for (int i=1;i<=n;i++) { for (int j=1;j<=m;j++) { scanf("%c", &a[i][j]); if (a[i][j]=='s') begin_x=i, begin_y=j; if (a[i][j]=='t') end_x=i, end_y=j; } getchar(); } dfs(begin_x, begin_y); if (flag) printf("YES\n"); else printf("NO\n"); } return 0; }