题解 | #迷宫问题#
迷宫问题
http://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
深度优先
#include <vector> #include <iostream> #include <sstream> #include <string> using namespace std; int n = 0; int m = 0; vector<pair<int, int>> theOne; vector<vector<int>> dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; void findPath(vector<vector<int>>& maze, vector<vector<bool>>& visited, int i, int j, vector<pair<int, int>>& path) { if (i < 0 || i >= n || j < 0 || j >= m || visited[i][j] || maze[i][j] == 1) return; if (i == n-1 && j == m-1) { path.push_back(make_pair(i, j)); theOne = path; return; } path.push_back(make_pair(i, j)); visited[i][j] = true; for (auto dir : dirs) { int next_x = i + dir[0]; int next_y = j + dir[1]; findPath(maze, visited, next_x, next_y, path); } path.pop_back(); visited[i][j] = false; } int main() { string s; while (cin >> n) { cin >> m; vector<vector<int>> maze(n, vector<int>(m, 0)); vector<vector<bool>> visited(n, vector<bool>(m, false)); vector<pair<int, int>> path; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { cin >> maze[i][j]; } } findPath(maze, visited, 0, 0, path); for (auto p : theOne) { cout << '(' << p.first << ',' << p.second << ')' << endl; } } return 0; }