题解 | #迷宫问题#

迷宫问题

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;
}
全部评论

相关推荐

点赞 评论 收藏
分享
10-17 10:05
已编辑
北华大学 全栈开发
牛客872465272号:掉头发了哥
点赞 评论 收藏
分享
评论
1
收藏
分享
牛客网
牛客企业服务