KatInterview

675. Cut Off Trees for Golf Event

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Sequenced BFS

The problem requires us to cut down all trees in a specific order: from shortest to tallest. This fixed order simplifies the problem significantly. Instead of finding a single optimal path that visits all trees (a variation of the Traveling Salesperson Problem), we can break it down into a series of smaller, independent shortest path problems.

Solution

Cut Off Trees for Golf Event in Python

import collections

class Solution:
    def cutOffTree(self, forest: list[list[int]]) -> int:
        m, n = len(forest), len(forest[0])

        # Step 1: Collect and sort trees. Python's tuple sorting works by default on the first element.
        trees = []
        for r in range(m):
            for c in range(n):
                if forest[r][c] > 1:
                    trees.append((forest[r][c], r, c)) # (height, r, c)
        
        trees.sort()

        # Helper BFS function to find shortest path between two points.
        def bfs(start_r, start_c, end_r, end_c):
            if start_r == end_r and start_c == end_c:
                return 0
            
            q = collections.deque([(start_r, start_c, 0)]) # (r, c, steps)
            visited = {(start_r, start_c)}
            
            while q:
                r, c, steps = q.popleft()

                for dr, dc in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
                    nr, nc = r + dr, c + dc
                    
                    # Check boundaries, walkability, and if not visited.
                    if 0 <= nr < m and 0 <= nc < n and \
                       forest[nr][nc] != 0 and (nr, nc) not in visited:
                        
                        # If we reached the target, return the distance.
                        if nr == end_r and nc == end_c:
                            return steps + 1
                        
                        visited.add((nr, nc))
                        q.append((nr, nc, steps + 1))
            
            return -1 # Target not reachable

        total_steps = 0
        start_r, start_c = 0, 0

        # Step 2: Sequentially find paths from current location to the next tree.
        for height, end_r, end_c in trees:
            steps = bfs(start_r, start_c, end_r, end_c)
            
            if steps == -1:
                return -1 # Cannot reach the next tree, so impossible.
            
            total_steps += steps
            # Update start position for the next iteration.
            start_r, start_c = end_r, end_c
            
        return total_steps

Cut Off Trees for Golf Event in Java

class Solution {
    int m, n;
    int[][] dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

    public int cutOffTree(List<List<Integer>> forest) {
        this.m = forest.size();
        this.n = forest.get(0).size();

        // Step 1: Collect and sort trees based on their height.
        List<int[]> trees = new ArrayList<>();
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (forest.get(i).get(j) > 1) {
                    trees.add(new int[]{forest.get(i).get(j), i, j}); // {height, r, c}
                }
            }
        }
        Collections.sort(trees, (a, b) -> Integer.compare(a[0], b[0]));

        int totalSteps = 0;
        int startR = 0;
        int startC = 0;

        // Step 2: Sequentially find paths from current location to the next tree.
        for (int[] tree : trees) {
            int endR = tree[1];
            int endC = tree[2];
            
            // Calculate shortest path distance using BFS.
            int steps = bfs(forest, startR, startC, endR, endC);

            if (steps == -1) {
                return -1; // Cannot reach the next tree, so impossible.
            }

            totalSteps += steps;
            
            // Update start position for the next iteration.
            startR = endR;
            startC = endC;
        }

        return totalSteps;
    }

    // BFS to find the shortest path from (sr, sc) to (er, ec).
    private int bfs(List<List<Integer>> forest, int sr, int sc, int er, int ec) {
        if (sr == er && sc == ec) {
            return 0;
        }

        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{sr, sc});
        
        boolean[][] visited = new boolean[m][n];
        visited[sr][sc] = true;
        
        int steps = 0;

        // Level-order traversal.
        while (!queue.isEmpty()) {
            int size = queue.size();
            steps++;
            for (int i = 0; i < size; i++) {
                int[] curr = queue.poll();
                
                for (int[] dir : dirs) {
                    int nr = curr[0] + dir[0];
                    int nc = curr[1] + dir[1];
                    
                    // Check boundaries, walkability, and if not visited.
                    if (nr >= 0 && nr < m && nc >= 0 && nc < n && 
                        !visited[nr][nc] && forest.get(nr).get(nc) != 0) {
                        
                        // If we reached the target, return the total steps for this path.
                        if (nr == er && nc == ec) {
                            return steps;
                        }
                        
                        visited[nr][nc] = true;
                        queue.offer(new int[]{nr, nc});
                    }
                }
            }
        }

        return -1; // Target not reachable.
    }
}

Cut Off Trees for Golf Event in C++

class Solution {
public:
    int cutOffTree(vector<vector<int>>& forest) {
        int m = forest.size();
        int n = forest[0].size();

        // Step 1: Collect and sort trees based on their height.
        vector<tuple<int, int, int>> trees;
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (forest[i][j] > 1) {
                    trees.emplace_back(forest[i][j], i, j);
                }
            }
        }
        sort(trees.begin(), trees.end());

        int total_steps = 0;
        int start_r = 0;
        int start_c = 0;

        // Step 2: Sequentially find paths from current location to the next tree.
        for (const auto& tree : trees) {
            int end_r = get<1>(tree);
            int end_c = get<2>(tree);

            // Calculate shortest path distance using BFS
            int steps = bfs(forest, start_r, start_c, end_r, end_c);
            
            if (steps == -1) {
                return -1; // Cannot reach the next tree, so impossible.
            }

            total_steps += steps;
            
            // Update start position for the next iteration.
            start_r = end_r;
            start_c = end_c;
        }

        return total_steps;
    }

private:
    // BFS to find the shortest path from (sr, sc) to (er, ec) in the forest.
    int bfs(const vector<vector<int>>& forest, int sr, int sc, int er, int ec) {
        if (sr == er && sc == ec) {
            return 0;
        }

        int m = forest.size();
        int n = forest[0].size();
        
        // Use a distance matrix that also acts as a visited check.
        vector<vector<int>> dist(m, vector<int>(n, -1));
        queue<pair<int, int>> q;
        
        q.push({sr, sc});
        dist[sr][sc] = 0;
        
        int dirs[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

        while (!q.empty()) {
            auto [r, c] = q.front();
            q.pop();

            for (auto& dir : dirs) {
                int nr = r + dir[0];
                int nc = c + dir[1];

                // Check boundaries, walkability, and if not visited.
                if (nr >= 0 && nr < m && nc >= 0 && nc < n && 
                    forest[nr][nc] != 0 && dist[nr][nc] == -1) {
                    
                    dist[nr][nc] = dist[r][c] + 1;

                    // If we reached the target, return the distance.
                    if (nr == er && nc == ec) {
                        return dist[nr][nc];
                    }
                    q.push({nr, nc});
                }
            }
        }

        return -1; // Target not reachable.
    }
};

Cut Off Trees for Golf Event in TypeScript

function cutOffTree(forest: number[][]): number {
    const m = forest.length;
    const n = forest[0].length;

    // Step 1: Collect and sort trees based on their height.
    const trees: [number, number, number][] = []; // [height, r, c]
    for (let r = 0; r < m; r++) {
        for (let c = 0; c < n; c++) {
            if (forest[r][c] > 1) {
                trees.push([forest[r][c], r, c]);
            }
        }
    }
    trees.sort((a, b) => a[0] - b[0]);

    // Helper BFS function to find the shortest path between two points.
    const bfs = (startR: number, startC: number, endR: number, endC: number): number => {
        if (startR === endR && startC === endC) {
            return 0;
        }

        const queue: [number, number, number][] = [[startR, startC, 0]]; // [r, c, steps]
        const visited: boolean[][] = Array(m).fill(0).map(() => Array(n).fill(false));
        visited[startR][startC] = true;
        
        const dirs = [[0, 1], [0, -1], [1, 0], [-1, 0]];
        let head = 0; // Use a pointer to simulate a queue for O(1) dequeue operations.

        while (head < queue.length) {
            const [r, c, steps] = queue[head++]; // Dequeue

            for (const [dr, dc] of dirs) {
                const nr = r + dr;
                const nc = c + dc;

                // Check boundaries, walkability, and if not visited.
                if (nr >= 0 && nr < m && nc >= 0 && nc < n && 
                    !visited[nr][nc] && forest[nr][nc] !== 0) {
                    
                    // If we reached the target, return the distance.
                    if (nr === endR && nc === endC) {
                        return steps + 1;
                    }

                    visited[nr][nc] = true;
                    queue.push([nr, nc, steps + 1]); // Enqueue
                }
            }
        }
        
        return -1; // Target not reachable
    };

    let totalSteps = 0;
    let startR = 0;
    let startC = 0;

    // Step 2: Sequentially find paths from current location to the next tree.
    for (const tree of trees) {
        const endR = tree[1];
        const endC = tree[2];

        const steps = bfs(startR, startC, endR, endC);
        
        if (steps === -1) {
            return -1; // Cannot reach the next tree, so impossible.
        }

        totalSteps += steps;
        // Update start position for the next iteration.
        startR = endR;
        startC = endC;
    }

    return totalSteps;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.