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文件

posted @ 2017-11-24 10:51  汪昕  阅读(1701)  评论(0编辑  收藏  举报