目录
题意:从S走到D,能不能恰好用T时间。
析:这个题时间是恰好,并不是少于T,所以用DFS来做,然后要剪枝,不然会TEL,我们这样剪枝,假设我们在(x,y),终点是(ex,ey),
那么从(x, y)到(ex, ey),要么时间正好是T-你已经走过的时间,要么要向别的地方先拐一下,以凑出这个正好时间,既然要拐一下,那么一定要回来,
所以时间肯定得是偶数,要不然完不成(回不来),
所以(t - abs(ex-x) - abs(ey-y) - cnt ),如果是奇数就剪枝。然而用C++交就TLE,用G++就AC。。。
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | #pragma comment(linker, "/STACK:1024000000,1024000000") #include <cstdio> #include <string> #include <cstdlib> #include <cmath> #include <iostream> #include <cstring> #include <set> #include <queue> #include <algorithm> #include <vector> #include <map> #include <cctype> using namespace std ; typedef long long LL; typedef pair< int , int > P; const int INF = 0x3f3f3f3f; const double inf = 0x3f3f3f3f3f3f3f; const double eps = 1e-8; const int maxn = 1e4 + 5; const int mod = 1e9 + 7; const int dr[] = {0, 0, -1, 1}; const int dc[] = {-1, 1, 0, 0}; int n, m; inline bool is_in( int r, int c){ return r >= 0 && r < n && c >= 0 && c < m; } int t; char s[10][10]; int vis[10][10]; int sx, sy, ex, ey; bool dfs( int r, int c, int cnt){ if (cnt > t) return false ; if (r == ex && c == ey && cnt == t) return true ; if ((t - abs (ex-r) - abs (ey-c) - cnt) & 1) return false ; for ( int i = 0; i < 4; ++i){ int x = dr[i] + r; int y = dc[i] + c; if (!is_in(x, y) || vis[x][y] || s[x][y] == 'X' ) continue ; vis[x][y] = 1; if (x == ex && ey == y && cnt + 1 == t) return true ; if ((t - abs (ex-x) - abs (ey-y) - cnt -1) & 1) continue ; if (dfs(x, y, cnt+1)) return true ; vis[x][y] = 0; } return false ; } int main(){ while ( scanf ( "%d %d %d" , &n, &m, & t) == 3){ if (!n && !m && !t) break ; for ( int i = 0; i < n; ++i) scanf ( "%s" , s[i]); for ( int i = 0; i < n; ++i) for ( int j = 0; j < m; ++j) if (s[i][j] == 'S' ) sx = i, sy = j; else if (s[i][j] == 'D' ) ex = i, ey = j; memset (vis, 0, sizeof (vis)); vis[sx][sy] = 1; if (dfs(sx, sy, 0)) puts ( "YES" ); else puts ( "NO" ); } return 0; } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步