1113. 红与黑
这道题注意要记录的是总步数,而不是当前步数
#include <iostream> #include <cstring> using namespace std; const int N = 105; char g[N][N]; int k, n; bool vis[N][N]; int sx, sy, ex, ey; int dx[] = {-1, 1, 0, 0}; int dy[] = {0, 0, -1, 1}; void dfs(int x, int y) { vis[x][y] = 1; if (x == ex && y == ey) return ; for(int i = 0; i < 4; i++) { int nx = x + dx[i], ny = y + dy[i]; if(nx < 0 || nx >= n || ny < 0 || ny >= n) continue; if(g[nx][ny] == '#') continue; if(vis[nx][ny]) continue; dfs(nx, ny); } } int main() { cin >> k; while (k--) { memset(vis, 0, sizeof vis); cin >> n; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { cin >> g[i][j]; } cin >> sx >> sy >> ex >> ey; if(g[sx][sy] == '#') { puts("NO"); continue; } dfs(sx, sy); if (vis[ex][ey]) puts("YES"); else puts("NO"); } return 0; }
错误示范:
void dfs(int x, int y, int step) { vis[x][y] = 1; if (x == ex && y == ey) { ans = max(ans, step); return; } for(int i = 0; i < 4; i++) { int nx = x + dx[i], ny = y + dy[i]; if(nx < 0 || nx >= n || ny < 0 || ny >= n) continue; if(g[nx][ny] == '#') continue; if(vis[nx][ny]) continue; dfs(nx, ny, step + 1); } }
这样子就只会统计当前点到源点的步数,而不是方块数量
本文作者:Gold_stein
本文链接:https://www.cnblogs.com/smartljy/p/17803745.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
2019-11-01 ACwing : 798. 差分矩阵