题解 | #地下迷宫#

地下迷宫

https://www.nowcoder.com/practice/571cfbe764824f03b5c0bfd2eb0a8ddf

#include <cmath>
#include <iostream>
#include <vector>
using namespace std;

const int N = 20;
int n, m, p;
int board[N][N];
bool st[N][N];

int x[4] = {0, 0, 1, -1};
int y[4] = {1, -1, 0, 0};
int r[4] = {1, 1, 0, 3};
// 坐标系的建立方向有讲究 
typedef pair<int, int> PII;


struct mypoint {
    vector<PII> points;
    int cost;
};

vector<mypoint> ans;
vector<PII> list;
void dfs(int i, int j, int p, int cost, vector<PII> list) {
    if (cost > p) return ;
    if (i == 0 && j == m - 1) {
        list.push_back({i, j});
        if (ans.size()) {
            if (cost < ans[0].cost) {
                ans[0].points = list;
                ans[0].cost = cost;
                return ;
            } else
                return ;
        } else ans.push_back({list, cost});

        return ;
    }

    list.push_back({i, j});
    st[i][j] = 1;

    for (int h = 0; h < 4; h++) {
        int x1 = i + x[h];
        int y1 = j + y[h];
        if (x1 < 0 || x1 >= n || y1 < 0 || y1 >= m || board[x1][y1] == 0 ||
                st[x1][y1] == 1)
            continue;


        dfs(x1, y1, p, cost + r[h], list);

    }
    list.pop_back();
    st[i][j] = 0;
}

int main() {
    cin >> n >> m >> p;

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cin >> board[i][j];
        }
    }

    dfs(0, 0, p, 0, list);
    if (ans.size() == 0) {
        cout << "Can not escape!" << endl;
    } else {
        for (int i = 0; i < ans[0].points.size(); i++) {
            cout << "[" << ans[0].points[i].first << "," << ans[0].points[i].second << "]";
            if (i != ans[0].points.size() - 1) {
                cout << ",";
            }
        }
        cout << endl;
    }


    return 0;

}

全部评论

相关推荐

one_t:硕还是本?什么岗
点赞 评论 收藏
分享
牛牛不牛牛3627:再找个稍微大一点的项目做一下然后搞懂,或者如果没时间了的话能八股背熟手撕都能做。建议就是多投多面,面完整理问的问题都搞懂,面多了你就大搞了解都会问什么问题了。主要还是八股,我当时就一个黑马点评也拿到大厂实习了,加油
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务