膜拜前面各位大佬,写一个最简单的辣鸡深度遍历

迷宫问题

http://www.nowcoder.com/questionTerminal/cf24906056f4488c9ddb132f317e03bc

#include <bits/stdc++.h>

using namespace std;

int N = 0, M = 0;
int pathlen = INT_MAX;
vector<vector<bool>> rec;
vector<pair<int, int>> pathrec;

void dfs(vector<vector<bool>> &maze, \
         vector<pair<int, int>> &path, \
         pair<int, int> cur, int len)
{
    if (cur.first == N-1&&cur.second == M-1) {
        len++;
        path.push_back(cur);
        if (pathlen>=len) {
            pathrec = path;
            pathlen = len;
        }
        path.pop_back();
        return;
    }
    else {
        int i = cur.first;
        int j = cur.second;
        rec[i][j] = true;
        path.push_back(make_pair(i, j));
        len++;
        // 向上
        if (i - 1 >= 0 &&( maze[i - 1][j] != true )&& (rec[i - 1][j] != true)) {
            dfs(maze, path, make_pair(i - 1, j), len);
        }
        // 向下
        if (i + 1<N&&(maze[i + 1][j] != true )&&( rec[i + 1][j] != true)) {
            dfs(maze, path, make_pair(i + 1, j), len);
        }
        // 向左
        if (j - 1 >= 0 && (maze[i][j - 1] != true) && (rec[i][j - 1] != true)) {
            dfs(maze, path, make_pair(i, j - 1), len);
        }
        // 向右
        if (j + 1<M&&(maze[i][j + 1] != true) && (rec[i][j + 1] != true)) {
            dfs(maze, path, make_pair(i, j + 1), len);
        }
        len--;
        path.pop_back();
        rec[i][j] = false;
    }
}


int main()
{
    // 深度优先遍历
    while (cin >> N >> M) {
        vector<vector<bool>> maze(N, vector<bool>(M, 0));
        int tn;tn = N;
        int tm;tm = M;
        // 迷宫输入完成
        for (int i = 0; i<N; i++) {
            for (int j = 0; j<M; j++) {
                int td; cin >> td;
                maze[i][j] = (td == 1) ? true : false;
            }
        }
        rec = maze;    // 已经经过的路径记录
        vector<pair<int, int>> path;
        dfs(maze, path, make_pair(0, 0), 0);
        for (int i = 0; i<pathrec.size(); i++) {
            cout << '(' << pathrec[i].first << ',' << pathrec[i].second << ')' << endl;
        }
        pathrec.clear();
        rec.clear();
        path.clear();
        maze.clear();
        pathlen = INT_MAX;
    }

    return 0;
}
全部评论

相关推荐

粗心的雪碧不放弃:纯学历问题,我这几个月也是一直优化自己的简历,后来发现优化到我自己都觉得牛逼的时候,发现面试数量也没有提升,真就纯学历问题
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务