LeeCode 675. Cut Off Trees for Golf Event

题意

给你一个二维矩阵表示森林,为0的地方不可行,大于1的地方表示树,值的大小就是树的高度,所有大于等于1的地方是可以走的,现在你从 (0,0) ( 0 , 0 ) 开始,按树的高度从小到大遍历所有的树,问最短路径。

题解

存下所有树的坐标,按树的高度从小大大依次用bfs求最短路径就好了。

代码

struct Node {
    int x, y, step;
    int h;
    bool operator==(const Node &b) const {
        return x == b.x && y == b.y;
    }
    bool operator<(const Node &b) const {
        return h < b.h;
    }
};

int moves[][2] = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } };

class Solution {
public:
    int cutOffTree(vector<vector<int>>& forest) {
        if (forest[0][0] == 0) {
            return -1;
        }
        vector<Node> v;
        for (int i = 0; i < forest.size(); i++) {
            for (int j = 0; j < forest[0].size(); j++) {
                if (forest[i][j] > 1) {
                    Node temp;
                    temp.x = i;
                    temp.y = j;
                    temp.step = 0;
                    temp.h = forest[i][j];
                    v.push_back(temp);
                }
            }
        }
        Node temp;
        temp.x = 0;
        temp.y = 0;
        temp.step = 0;
        temp.h = 0;
        v.push_back(temp);
        sort(v.begin(), v.end());
        int ans = 0;
        for (int i = 0; i < v.size() - 1; i++) {
            int temp = bfs(v[i], v[i + 1], forest);
            if (temp == -1) {
                return -1;
            }else{
                ans += temp;
            }
        }
        return ans;
    }
    int bfs(Node st, Node ed, vector<vector<int>>& forest) {
        st.step = 0;
        queue<Node> q;
        q.push(st);
        int mark[51][51];
        memset(mark, 0, sizeof(mark));
        mark[st.x][st.y] = 1;
        while (!q.empty()) {
            Node n = q.front();
            q.pop();
            if (n == ed) {
                return n.step;
            }
            for (int i = 0; i < 4; i++) {
                Node temp = n;
                temp.step++;
                temp.x += moves[i][0];
                temp.y += moves[i][1];
                if (temp.x < 0 || temp.x >= forest.size() || temp.y < 0 || temp.y >= forest[0].size()) {
                    continue;
                }

                if (mark[temp.x][temp.y]) {
                    continue;
                }
                if (forest[temp.x][temp.y] == 0) {
                    continue;
                }
                mark[temp.x][temp.y] = 1;
                q.push(temp);
            }
        }
        return -1;
    }

};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值