为高尔夫比赛砍树(来源力扣)

这篇博客介绍了如何解决一个数据结构与算法问题,即在二维森林矩阵中找到一条从根节点到最远节点的最短路径,通过BFS实现。代码中定义了一个Solution类,包含了主要的cutOffTree方法和辅助的bfs方法,用于遍历森林并计算步数。算法首先找出所有高度大于1的树,然后按高度排序,依次进行BFS搜索,最终返回总步数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
思路:在这里插入图片描述

class Solution {
    int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    public int cutOffTree(List<List<Integer>> forest) {
        List<int[]> trees = new ArrayList<int[]>();
        int row = forest.size();
        int col = forest.get(0).size();
        for(int i = 0; i < row; i++) {
            for(int j = 0; j < col; j++) {
                if(forest.get(i).get(j) > 1) {
                    trees.add(new int[] {i, j});
                }
            }
        }
        Collections.sort(trees, (a, b) -> forest.get(a[0]).get(a[1]) - forest.get(b[0]).get(b[1]));
        int cx = 0;
        int cy = 0;
        int ans = 0;
        for(int i = 0; i < trees.size(); i++) {
            int steps = bfs(forest, cx, cy, trees.get(i)[0], trees.get(i)[1]);
            if(steps == -1) {
                return -1;
            }
            ans += steps;
            cx = trees.get(i)[0];
            cy = trees.get(i)[1];
        }
        return ans;
    }
    private int bfs(List<List<Integer>> forest, int sx, int sy, int tx, int ty) {
        if(sx == tx && sy == ty) {
            return 0;
        }
        int row = forest.size();
        int col = forest.get(0).size();
        int step = 0;
        Queue<int[]> queue = new ArrayDeque<int[]>();
        boolean[][] visited = new boolean[row][col];
        queue.offer(new int[] {sx, sy});
        visited[sx][sy] = true;
        while(!queue.isEmpty()) {
            step++;
            int sz = queue.size();
            for(int i = 0; i < sz; i++) {
                int[] cell = queue.poll();
                int cx = cell[0], cy = cell[1];
                for(int j = 0; j < 4; j++) {
                    int nx = cx + dirs[j][0];
                    int ny = cy + dirs[j][1];
                    if(nx >= 0 && nx < row && ny >= 0 && ny < col) {
                        if(!visited[nx][ny] && forest.get(nx).get(ny) > 0) {
                            if(nx == tx && ny == ty) {
                                return step;
                            }
                            queue.offer(new int[] {nx, ny});
                            visited[nx][ny] = true;
                        }
                    }
                }
            }
        }
        return -1;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值