超时了,dfs写的是对的(通过了discuss中一块强大的数据)
谁说TLE的代码没有用?
# include <stdio.h> # include <string.h> typedef struct{ int x, y; }Point; const Point d[4] = {{-1,0}, {0,1}, {0,-1}, {1,0}}; int N, M, T, tot, ok; char m[8][8]; int dfs(Point s, int dir); int can_move(Point s, int dir); void solve(Point s, Point e, int T); int main() { int i; char *p; Point s, e; freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); while (1) { scanf("%d%d%d", &N, &M, &T); if (!N && !M && !T) break; memset(m, 0, sizeof(m)); for ( i = 1; i <= N; ++i) { scanf("%s", m[i]+1); if ((p = strchr(m[i]+1, 'S')) != NULL) {s.x = i; s.y = p-m[i];} if ((p = strchr(m[i]+1, 'D')) != NULL) {e.x = i; e.y = p-m[i];} } solve(s, e, T); } return 0; } int dfs(Point s, int dir) { int ddir, f; f = 0; ++tot; s.x = s.x + d[dir].x; s.y = s.y + d[dir].y; if (m[s.x][s.y] == 'D') f = 1; if (tot == T && f) return ok = 1; m[s.x][s.y] = 'L'; for ( ddir = 0; ddir < 4; ++ddir) { if (ddir != 3-dir && can_move(s, ddir)) dfs(s, ddir); } --tot; if (!f)m[s.x][s.y] = '.'; else m[s.x][s.y] = 'D'; } int can_move(Point s, int dir) { Point nx; nx.x = s.x + d[dir].x; nx.y = s.y + d[dir].y; if (1 <= nx.x && nx.x <= N && 1 <= nx.y && nx.y <= M && (m[nx.x][nx.y] == '.' || m[nx.x][nx.y] == 'D')) return 1; return 0; } void solve(Point s, Point e, int T) { int dir; if (T >= N*M) {printf("NO\n"); return ;} if (m[s.x][s.y] == 'D') { if (T == 0) printf("YES\n"); else printf("NO\n"); return ; } m[s.x][s.y] = 'L'; for (ok = dir = 0; dir < 4; ++dir) { tot = 0; if (can_move(s, dir) && !ok) { dfs(s, dir); } } printf(ok==1 ? "YES\n":"NO\n"); }