LintCode & LeetCode
  • Introduction
  • Linked List
    • Sort List
    • Merge Two Sorted Lists
    • Merge k Sorted Lists
    • Linked List Cycle
    • Linked List Cycle II
    • Add Two Numbers II
    • Add Two Numbers
    • Odd Even Linked List
    • Intersection of Two Linked Lists
    • Reverse Linked List
    • Reverse Linked List II
    • Remove Linked List Elements
    • Remove Nth Node From End of List
    • Middle of the Linked List
    • Design Linked List
      • Design Singly Linked List
      • Design Doubly Linked List
    • Palindrome Linked List
    • Remove Duplicates from Sorted List
    • Remove Duplicates from Sorted List II
    • Implement Stack Using Singly Linked List
    • Copy List with Random Pointer
  • Binary Search
    • Search in Rotated Sorted Array
    • Search in Rotated Sorted Array II
    • Search in a Sorted Array of Unknown Size
    • First Bad Version
    • Find Minimum in Rotated Sorted Array
    • Find Minimum in Rotated Sorted Array II
    • Find Peak Element
    • Search for a Range
    • Find K Closest Elements
    • Search Insert Position
    • Peak Index in a Mountain Array
    • Heaters
  • Hash Table
    • Jewels and Stones
    • Single Number
    • Subdomain Visit Count
    • Design HashMap
    • Design HashSet
    • Logger Rate Limiter
    • Isomorphic Strings
    • Minimum Index Sum of Two Lists
    • Contains Duplicate II
    • Contains Duplicate III
    • Longest Consecutive Sequence
    • Valid Sudoku
    • Distribute Candies
    • Shortest Word Distance
    • Shortest Word Distance II
  • String
    • Rotate String
    • Add Binary
    • Implement strStr()
    • Longest Common Prefix
    • Reverse Words in a String
    • Reverse Words in a String II
    • Reverse Words in a String III
    • Valid Word Abbreviation
    • Group Anagrams
    • Unique Email Addresses
    • Next Closest Time
    • License Key Formatting
    • String to Integer - atoi
    • Ransom Note
    • Multiply Strings
    • Text Justification
    • Reorder Log Files
    • Most Common Word
    • Valid Parenthesis String
    • K-Substring with K different characters
    • Find All Anagrams in a String
    • Find the Closest Palindrome
    • Simplify Path
  • Array
    • Partition Array
    • Median of Two Sorted Arrays
    • Intersection of Two Arrays
    • Intersection of Two Arrays II
    • Maximum Subarray Sum
    • Minimum Subarray Sum
    • Maximum Subarray II
    • Maximum Subarray III
    • Subarray Sum Closest
    • Subarray Sum
    • Plus One
    • Maximum Subarray Difference
    • Maximum Subarray IV
    • Subarray Sum Equals K
    • Intersection of Two Arrays
    • Intersection of Two Arrays II
    • Find Pivot Index
    • Rotate Array
    • Get Smallest Nonnegative Integer Not In The Array
    • Maximize Distance to Closest Person
    • Sort Colors
    • Next Permutation
    • Rotate Image
    • Pour Water
    • Prison Cells After N Days
    • Majority Element
    • Can Place Flowers
    • Candy
  • Matrix
    • Spiral Matrix
    • Set Matrix Zeroes
    • Diagonal Traverse
  • Queue
    • Design Circular Queue
    • Implement Queue using Stacks
    • Implement Queue by Two Stacks
    • Implement Stack using Queues
    • Moving Average from Data Stream
    • Walls and Gates
    • Open the Lock
    • Sliding Window Maximum
    • Implement Queue Using Fixed Length Array
    • Animal Shelter
  • Stack
    • Valid Parentheses
    • Longest Valid Parentheses
    • Min Stack
    • Max Stack
    • Daily Temperatures
    • Evaluate Reverse Polish Notation
    • Next Greater Element I
    • Next Greater Element II
    • Next Greater Element III
    • Largest Rectangle in Histogram
    • Maximal Rectangle
    • Car Fleet
  • Heap
    • Trapping Rain Water II
    • The Skyline Problem
    • Top K Frequent Words
    • Top K Frequent Words II
    • Top K Frequent Elements
    • Top k Largest Numbers
    • Top k Largest Numbers II
    • Minimum Cost to Hire K Workers
    • Kth Largest Element in an Array
    • Kth Smallest Number in Sorted Matrix
    • Kth Smallest Sum In Two Sorted Arrays
    • K Closest Points to the Origin
    • Merge K Sorted Lists
    • Merge K Sorted Arrays
    • Top K Frequent Words - Map Reduce
  • Data Structure & Design
    • Hash Function
    • Heapify
    • LRU Cache
    • LFU Cache
    • Rehashing
    • Stack Sorting
    • Animal Shelter
    • Sliding Window Maximum
    • Moving Average from Data Stream
    • Find Median from Data Stream
    • Sliding Window Median
    • Design Hit Counter
    • Read N Characters Given Read4 II - Call multiple times
    • Read N Characters Given Read4
    • Flatten 2D Vector
    • Flatten Nested List Iterator
    • Design Search Autocomplete System
    • Time Based Key-Value Store
    • Design Tic-Tac-Toe
    • Insert Delete GetRandom O(1)
  • Union Find
    • Find the Connected Component in the Undirected Graph
    • Find the Weak Connected Component in the Directed Graph
    • Graph Valid Tree
    • Number of Islands
    • Number of Islands II
    • Surrounded Regions
    • Most Stones Removed with Same Row or Column
    • Redundant Connection
  • Trie
    • Implement Trie
    • Add and Search Word
    • Word Search II
    • Longest Word in Dictionary
    • Palindrome Pairs
    • Trie Serialization
    • Trie Service
    • Design Search Autocomplete System
    • Typeahead
  • Trees
    • Binary Tree Inorder Traversal
    • Binary Tree Postorder Traversal
    • Binary Tree Preorder Traversal
    • Binary Tree Level Order Traversal
    • Binary Tree Zigzag Level Order Traversal
    • Binary Tree Vertical Order Traversal
    • N-ary Tree Level Order Traversal
    • N-ary Tree Preorder Traversal
    • N-ary Tree Postorder Traversal
    • Construct Binary Tree from Preorder and Inorder Traversal
    • Populating Next Right Pointers in Each Node
    • Populating Next Right Pointers in Each Node II
    • Maximum Depth of Binary Tree
    • Symmetric Tree
    • Validate Binary Search Tree
    • Convert Sorted Array to Binary Search Tree
    • Path Sum
    • Path Sum II
    • Path Sum III
    • Binary Tree Maximum Path Sum
    • Kth Smallest Element in a BST
    • Same Tree
    • Lowest Common Ancestor of a Binary Tree
    • Lowest Common Ancestor of a Binary Search Tree
    • Nested List Weight Sum II
    • BST Node Distance
    • Minimum Distance (Difference) Between BST Nodes
    • Closet Common Manager
    • N-ary Tree Postorder Traversal
    • Serialize and Deserialize Binary Tree
    • Serialize and Deserialize N-ary Tree
    • Diameter of a Binary Tree
    • Print Binary Trees
  • Segment Tree
    • Segment Tree Build
    • Range Sum Query - Mutable
  • Binary Indexed Tree
  • Graph & Search
    • Clone Graph
    • N Queens
    • Six Degrees
    • Number of Islands
    • Number of Distinct Islands
    • Word Search
    • Course Schedule
    • Course Schedule II
    • Word Ladder
    • Redundant Connection
    • Redundant Connection II
    • Longest Increasing Path in a Matrix
    • Reconstruct Itinerary
    • The Maze
    • The Maze II
    • The Maze III
    • Topological Sorting
    • Island Perimeter
    • Flood Fill
    • Cheapest Flights Within K Stops
    • Evaluate Division
    • Alien Dictionary
    • Cut Off Trees for Golf Event
    • Jump Game II
    • Most Stones Removed with Same Row or Column
  • Backtracking
    • Subsets
    • Subsets II
    • Letter Combinations of a Phone Number
    • Permutations
    • Permutations II
    • Combinations
    • Combination Sum
    • Combination Sum II
    • Combination Sum III
    • Combination Sum IV
    • N-Queens
    • N-Queens II
    • Generate Parentheses
    • Subsets of Size K
  • Two Pointers
    • Two Sum II
    • Triangle Count
    • Trapping Rain Water
    • Container with Most Water
    • Minimum Size Subarray Sum
    • Minimum Window Substring
    • Longest Substring Without Repeating Characters
    • Longest Substring with At Most K Distinct Characters
    • Longest Substring with At Most Two Distinct Characters
    • Fruit Into Baskets
    • Nuts & Bolts Problem
    • Valid Palindrome
    • The Smallest Difference
    • Reverse String
    • Remove Element
    • Max Consecutive Ones
    • Max Consecutive Ones II
    • Remove Duplicates from Sorted Array
    • Remove Duplicates from Sorted Array II
    • Move Zeroes
    • Longest Repeating Character Replacement
    • 3Sum With Multiplicity
    • Merge Sorted Array
    • 3Sum Smaller
    • Backspace String Compare
  • Mathematics
    • Ugly Number
    • Ugly Number II
    • Super Ugly Number
    • Sqrt(x)
    • Random Number 1 to 7 With Equal Probability
    • Pow(x, n)
    • Narcissistic Number
    • Rectangle Overlap
    • Happy Number
    • Add N Days to Given Date
    • Reverse Integer
    • Greatest Common Divisor or Highest Common Factor
  • Bit Operation
    • IP to CIDR
  • Random
    • Random Pick with Weight
    • Random Pick Index
    • Linked List Random Node
  • Dynamic Programming
    • House Robber
    • House Robber II
    • House Robber III
    • Longest Increasing Continuous Subsequence
    • Longest Increasing Continuous Subsequence II
    • Coins in a Line
    • Coins in a Line II
    • Coins in a Line III
    • Maximum Product Subarray
    • Longest Palindromic Substring
    • Stone Game
    • Burst Balloons
    • Perfect Squares
    • Triangle
    • Pascal's Triangle
    • Pascal's Triangle II
    • Min Cost Climbing Stairs
    • Climbing Stairs
    • Unique Paths
    • Unique Paths II
    • Minimum Path Sum
    • Word Break
    • Word Break II
    • Range Sum Query - Immutable
    • Decode Ways
    • Edit Distance
    • Unique Binary Search Trees
    • Unique Binary Search Trees II
    • Maximal Rectangle
    • Maximal Square
    • Regular Expression Matching
    • Wildcard Matching
    • Flip Game II
    • Longest Increasing Subsequence
    • Target Sum
    • Partition Equal Subset Sum
    • Coin Change
    • Jump Game
    • Can I Win
    • Maximum Sum Rectangle in a 2D Matrix
    • Cherry Pick
  • Knapsack
    • Backpack
    • Backpack II
    • Backpack III
    • Backpack IV
    • Backpack V
    • Backpack VI
    • Backpack VII
    • Coin Change
    • Coin Change II
  • High Frequency
    • 2 Sum Closest
    • 3 Sum
    • 3 Sum Closest
    • Sort Colors II
    • Majority Number
    • Majority Number II
    • Majority Number III
    • Best Time to Buy and Sell Stock
    • Best Time to Buy and Sell Stock II
    • Best Time to Buy and Sell Stock III
    • Best Time to Buy and Sell Stock IV
    • Two Sum
    • Two Sum II - Input array is sorted
    • Two Sum III - Data structure design
    • Two Sum IV - Input is a BST
    • 4 Sum
    • 4 Sum II
  • Sorting
  • Greedy
    • Jump Game II
    • Remove K Digits
  • Minimax
    • Nim Game
    • Can I Win
  • Sweep Line & Interval
    • Meeting Rooms
    • Meeting Rooms II
    • Merge Intervals
    • Insert Interval
    • Number of Airplanes in the Sky
    • Exam Room
    • Employee Free Time
    • Closest Pair of Points
    • My Calendar I
    • My Calendar II
    • My Calendar III
    • Add Bold Tag in String
  • Other Algorithms and Data Structure
    • Huffman Coding
    • Reservoir Sampling
    • Bloom Filter
    • External Sorting
    • Construct Quad Tree
  • Company Tag
    • Google
      • Guess the Word
      • Raindrop on Sidewalk
    • Airbnb
      • Display Pages (Pagination)
    • Amazon
  • Problem Solving Summary
    • String or Array Rotation
    • Tips for Avoiding Bugs
    • Substring or Subarray Search
    • Sliding Window
    • K Sums
    • Combination Sum Series
    • Knapsack Problems
    • Depth-first Search
    • Large Number Operation
    • Implementation - Simulation
    • Monotonic Stack & Queue
    • Top K Problems
    • Java Interview Tips
      • OOP in Java
      • Conversion in Java
      • Data Structures in Java
    • Algorithm Optimization Tips
  • Reference
Powered by GitBook
On this page
  • Solution & Analysis
  • 基本框架:
  • BFS
  • Another BFS (Store distance in int[] {r, c, dist})
  • Dijkstra's Algorithm (Greedy + PriorityQueue based)
  • Approach: A* Search
  • Approach: Hadlock's Algorithm
  • Reference

Was this helpful?

  1. Graph & Search

Cut Off Trees for Golf Event

Graph, Breadth-first Search, Shortest Path

Hard

You are asked to cut off trees in a forest for a golf event. The forest is represented as a non-negative 2D map, in this map:

  1. 0 represents the obstacle can't be reached.

  2. 1 represents the ground can be walked through.

  3. The place with number bigger than 1 represents a tree can be walked through, and this positive number represents the tree's height.

You are asked to cut off all the trees in this forest in the order of tree's height - always cut off the tree with lowest height first. And after cutting, the original place has the tree will become a grass (value 1).

You will start from the point (0, 0) and you should output the minimum steps you need to walk to cut off all the trees. If you can't cut off all the trees, output -1 in that situation.

You are guaranteed that no twotreeshave the same height and there is at least one tree needs to be cut off.

Example 1:

Input:

[
 [1,2,3],
 [0,0,4],
 [7,6,5]
]

Output:
 6

Example 2:

Input:

[
 [1,2,3],
 [0,0,0],
 [7,6,5]
]

Output:
 -1

Example 3:

Input:

[
 [2,3,4],
 [0,0,5],
 [8,7,6]
]

Output:
 6

Explanation:
 You started from the point (0,0) and you can cut off the tree in (0,0) directly without walking.

Hint: size of the given matrix will not exceed 50x50.

Solution & Analysis

跟The Maze系列有些类似;都是寻找最短路径,但是这里要计算每次从新起点到下一棵要砍的树的最短距离,所以shortest distance需要被call多次(每次砍树都要先call)。

基本框架:

  • 先找到所有的树,按照高度从低到高排序

  • 从(0,0)作为起点,每次都寻找到下一棵树的最短路径长度,并更新总步数长度;以及更新起点位置和下一个目标位置

  • 如果最短路径不存在,返回-1。

最短路径的寻找方式有许多种,在grid类型的graph中,有十分简便的实现:

因为grid类型的graph可以看成edge的weight/length均为1的无向图,因此BFS可以一层一层地遍历,到达目标点的总步长也就是遍历的层数,每一层开始前记录当前层中节点数量,遍历完之后,再遍历下一层,放在queue中的是每一层的节点。如果找到目标位置,则返回当前的层数即可。

BFS

class Solution {
    public int cutOffTree(List<List<Integer>> forest) {
        // Get all the trees with h-height, r-row, c-column and sort by height
        List<int[]> trees = new ArrayList<>();
        int[][] map = new int[forest.size()][forest.get(0).size()];
        for (int r = 0; r < forest.size(); r++) {
            for (int c = 0; c < forest.get(r).size(); c++) {
                int h = forest.get(r).get(c);
                map[r][c] = h;
                if (h > 1) {
                    trees.add(new int[] {h, r, c});
                }
            }
        }

        // Sort trees based on height of trees
        Collections.sort(trees, (t1, t2) -> Integer.compare(t1[0], t2[0]));

        int ans = 0;
        int r0 = 0;
        int c0 = 0;
        // Find distance from current position to next tree
        for (int[] tree: trees) {
            int d = dist(map, r0, c0, tree[1], tree[2]);
            if (d < 0) {
                return -1;
            }
            ans += d;
            r0 = tree[1];
            c0 = tree[2];
        }
        return ans;
    }

    private static int[][] dirs = {{-1, 0}, {1, 0} , {0, -1}, {0, 1}};

    private int dist(int[][] map, int sr, int sc, int tr, int tc) {
        int distance = 0;
        boolean[][] visited = new boolean[map.length][map[0].length];
        Queue<int[]> q = new LinkedList<int[]>();
        q.offer(new int[] {sr, sc});
        visited[sr][sc] = true;

        while (!q.isEmpty()) {
            int levelSize = q.size();
            while (levelSize-- > 0) {
                int[] pos = q.poll();

                if (pos[0] == tr && pos[1] == tc) {
                    return distance;
                }

                for (int[] dir: dirs) {
                    int nr = pos[0] + dir[0];
                    int nc = pos[1] + dir[1];
                    if (nr >= 0 && nr < map.length && nc >= 0 && nc < map[0].length) {
                        if (map[nr][nc] != 0 && !visited[nr][nc]) {
                            q.offer(new int[] {nr, nc});
                            visited[nr][nc] = true;
                        }
                    }
                }
            }
            distance++;
        }
        return -1;
    }
}

Another BFS (Store distance in int[] {r, c, dist})

类似上面的一层一层BFS,这里就是把距离放到每个节点的int[]中.

Runtime: 258 ms, faster than 84.21% of Java online submissions for Cut Off Trees for Golf Event.

Memory Usage: 46.7 MB, less than 100.00% of Java online submissions for Cut Off Trees for Golf Event.

class Solution {
    public int cutOffTree(List<List<Integer>> forest) {
        // Get all the trees with h-height, r-row, c-column and sort by height
        List<int[]> trees = new ArrayList<>();
        int[][] map = new int[forest.size()][forest.get(0).size()];
        for (int r = 0; r < forest.size(); r++) {
            for (int c = 0; c < forest.get(r).size(); c++) {
                int h = forest.get(r).get(c);
                map[r][c] = h;
                if (h > 1) {
                    trees.add(new int[] {h, r, c});
                }
            }
        }

        // Sort trees based on height of trees
        Collections.sort(trees, (t1, t2) -> Integer.compare(t1[0], t2[0]));

        int ans = 0;
        int r0 = 0;
        int c0 = 0;
        // Find distance from current position to next tree
        for (int[] tree: trees) {
            int d = dist(forest, r0, c0, tree[1], tree[2]);
            if (d < 0) {
                return -1;
            }
            ans += d;
            r0 = tree[1];
            c0 = tree[2];
        }
        return ans;
    }

    private static int[][] dirs = {{-1, 0}, {1, 0} , {0, -1}, {0, 1}};

    public int dist(List<List<Integer>> forest, int sr, int sc, int tr, int tc) {
        int R = forest.size(), C = forest.get(0).size();
        Queue<int[]> queue = new LinkedList();
        boolean[][] seen = new boolean[R][C];

        queue.add(new int[]{sr, sc, 0});
        seen[sr][sc] = true;

        while (!queue.isEmpty()) {
            int[] cur = queue.poll();
            if (cur[0] == tr && cur[1] == tc) {
                return cur[2];
            }
            for (int[] dir: dirs) {
                int r = cur[0] + dir[0];
                int c = cur[1] + dir[1];
                if (0 <= r && r < R && 0 <= c && c < C &&
                    !seen[r][c] && forest.get(r).get(c) > 0) {
                    seen[r][c] = true;
                    queue.add(new int[]{r, c, cur[2] + 1});
                }
            }
        }
        return -1;
    }
}

Dijkstra's Algorithm (Greedy + PriorityQueue based)

与BFS的区别就在于不再是一层一层遍历,而是每次通过在PriorityQueue中poll(),得到当前待遍历的节点中到起始点距离最短的节点,然后四方向寻找,如果发现距离比distance[][] matrix所记录的要小,就更新distance[][]matrix,并且将该节点以及其到起始点的距离放入PriorityQueue中,进行下一轮poll()的过程。

Performance:

  • Runtime: 911 ms, faster than 3.64% of Java online submissions for Cut Off Trees for Golf Event.

  • Memory Usage: 46.7 MB, less than 100.00% of Java online submissions for Cut Off Trees for Golf Event.

class Solution {
    public int cutOffTree(List<List<Integer>> forest) {
        // Get all the trees with h-height, r-row, c-column and sort by height
        List<int[]> trees = new ArrayList<>();
        int[][] map = new int[forest.size()][forest.get(0).size()];
        for (int r = 0; r < forest.size(); r++) {
            for (int c = 0; c < forest.get(r).size(); c++) {
                int h = forest.get(r).get(c);
                map[r][c] = h;
                if (h > 1) {
                    trees.add(new int[] {h, r, c});
                }
            }
        }

        // Sort trees based on height of trees
        Collections.sort(trees, (t1, t2) -> Integer.compare(t1[0], t2[0]));

        int ans = 0;
        int r0 = 0;
        int c0 = 0;
        // Find distance from current position to next tree
        for (int[] tree: trees) {
            int d = dist(map, r0, c0, tree[1], tree[2]);
            if (d < 0) {
                return -1;
            }
            ans += d;
            r0 = tree[1];
            c0 = tree[2];
        }
        return ans;
    }

    private static int[][] dirs = {{-1, 0}, {1, 0} , {0, -1}, {0, 1}};

    // Dijkstra's Algorithm to Find Shortest Distance
    private int dist(int[][] map, int sr, int sc, int tr, int tc) {

        // Init distance matrix
        int[][] distance = new int[map.length][map[0].length];
        for (int[] row: distance) {
            Arrays.fill(row, Integer.MAX_VALUE);
        }
        distance[sr][sc] = 0;

        // Init priority queue for vertices to traverse
        PriorityQueue<int[]> q = new PriorityQueue<int[]>((a, b) -> a[2] - b[2]);
        q.offer(new int[] {sr, sc, 0});

        while (!q.isEmpty()) {
            int[] pos = q.poll();

            for (int[] dir: dirs) {
                int nr = pos[0] + dir[0];
                int nc = pos[1] + dir[1];
                if (nr >= 0 && nr < map.length && nc >= 0 && nc < map[0].length) {
                    // Update distance matrix and add the vertex to priority queue
                    if (map[nr][nc] != 0 && (pos[2] + 1 < distance[nr][nc])) {
                        distance[nr][nc] = pos[2] + 1;
                        q.offer(new int[] {nr, nc, pos[2] + 1});
                    }
                }
            }
        }

        if (distance[tr][tc] == Integer.MAX_VALUE) {
            return -1;
        }
        return distance[tr][tc];
    }
}

Approach: A* Search

Approach: Hadlock's Algorithm

Reference

PreviousAlien DictionaryNextJump Game II

Last updated 5 years ago

Was this helpful?

TODO:

TODO:

https://leetcode.com/articles/cutoff-trees-for-golf-event/?orderBy=most_votes
https://leetcode.com/articles/cutoff-trees-for-golf-event/?orderBy=most_votes
http://www.cnblogs.com/grandyang/p/8379506.html