DFS-深度优先算法解决迷宫问题

/*
main.cpp
*/
#define
_CRT_SECURE_NO_WARNINGS #include<iostream> using namespace std; int sr, sc, dr, dc; int R,C,minLen = 100; char grid[10][10]; bool found[10][10]; void dfs(int r, int c, int len); int main() { freopen("./data.in", "r", stdin); cin >> R >> C; for (int i = 0; i < R;i++) for (int j = 0; j < C; j++) { cin >> grid[i][j]; if (grid[i][j] == 'S'){ sr = i; sc = j; } if (grid[i][j] == 'D'){ dr = i; dc = j; } found[i][j] = false; } dfs(sr, sc, 0); cout << minLen << endl; return 0; } int d[4][2] = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } }; void dfs(int r, int c, int len) { if (r == dr&&c == dc) { if (minLen > len) minLen = len; return; } for (int i = 0; i < 4; i++) { int nextR = r + d[i][0]; int nextC = c + d[i][1]; if (nextR < 0 || nextR >= R || nextC < 0 || nextC >= C) continue; if (grid[nextR][nextC] == 'X') continue; if (found[nextR][nextC] == true) continue; found[nextR][nextC] = true; dfs(nextR, nextC, len + 1); found[nextR][nextC] = false; } }
6 6
S.XD..
..XXX.
...X..
......

data.in文件

全部评论

相关推荐

Twilight_m...:经典我朋友XXXX起手,这是那种经典的不知道目前行情搁那儿胡编乱造瞎指导的中年人,不用理这种**
点赞 评论 收藏
分享
zzzzhz:兄弟你先猛猛投简历至少三百家,能约到面试就去面。最近可以速成智能小车,智慧家居烂大街的项目,不需要自己写,只需要把里面的代码讲解看明白就行。把其中涉及到的八股文都拿出来单独背一下,我去年找工作就一个智能小车智慧家居找了10k差不多。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务