Skip to content

Latest commit

 

History

History
273 lines (220 loc) · 7.38 KB

675.Cut-Off-Trees-for-Golf-Event.md

File metadata and controls

273 lines (220 loc) · 7.38 KB

675. Cut Off Trees for Golf Event


题目地址

https://leetcode.com/problems/cut-off-trees-for-golf-event/

题目描述

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:

0 represents the obstacle can't be reached.
1 represents the ground can be walked through.
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 two trees have 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.

代码

Approach #0 BFS

class Solution {
    static int[][] dir = {{0,1}, {0, -1}, {1, 0}, {-1, 0}};

    public int cutOffTree(List<List<Integer>> forest) {
        if (forest == null || forest.size() == 0) return 0;
        int m = forest.size(), n = forest.get(0).size();

        PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[2] - b[2]);

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (forest.get(i).get(j) > 1) {
                    pq.add(new int[] {i, j, forest.get(i).get(j)});
                }
            }
        }

        int[] start = new int[2];
        int sum = 0;
        while (!pq.isEmpty()) {
            int[] tree = pq.poll();
            int step = minStep(forest, start, tree, m, n);

            if (step < 0) return -1;
            sum += step;

            start[0] = tree[0];
            start[1] = tree[1];
        }

        return sum;
    }

    private int minStep(List<List<Integer>> forest, int[] start, int[] tree, int m, int n) {
        int step = 0;
        boolean[][] visited = new boolean[m][n];
        Queue<int[]> queue = new LinkedList<>();
        queue.add(start);
        visited[start[0]][start[1]] = true;

        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                int[] curr = queue.poll();
                if (curr[0] == tree[0] && curr[1] == tree[1]) return step;

                for (int[] d : dir) {
                    int nr = curr[0] + d[0];
                    int nc = curr[1] + d[1];
                    if (nr < 0 || nr >= m || nc < 0 || nc >= n 
                        || forest.get(nr).get(nc) == 0 || visited[nr][nc]) continue;
                    queue.add(new int[] {nr, nc});
                    visited[nr][nc] = true;
                }
            }
            step++;
        }

        return -1;
    }
}

Approach #1

Complexity Analysis

All three algorithms have similar worst case complexities, but in practice each successive algorithm presented performs faster on random data.

  • Time Complexity: O((RC)^2) where there are Rrows and C columns in the givenforest. We walk to R_C_ trees, and each walk could spend O(R*C) time searching for the tree.
  • Space Complexity: O(R*C), the maximum size of the data structures used.
class Solution {
  int[] dr = {-1, 1, 0, 0};
  int[] dc = {0, 0, -1, 1};

  public int cutOffTree(List<List<Integer>> forest) {
    List<int[]> trees = new ArrayList();
    for (int r = 0; r < forest.size(); r++) {
      for (int c = 0; c < forest.get(0).size(); c++) {
        int v = forest.get(r).get(c);
        if (v > 1) trees.add(new int[]{v, r, c});
      }
    }

    Collections.sort(trees, (a, b) -> Integer.compare(a[0], b[0]));

    int ans = 0, sr = 0, sc = 0;
    for (int[] tree : trees) {

      int d = dist(forest, sr, sc, tree[1], tree[2]); // be repalced by the following method

      if (d < 0)    return -1;
      ans += d;
      sr = tree[1];
      sc = tree[2];
    }

    return ans;
  }
}

Approach #1 BFS

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

  boolean[][] seen = new boolean[R][C];
  seen[sr][sc] = true;
  while (!queue.isEmpty()) {
    int[] cur = queue.poll();
    if (cur[0] == tr && cur[1] == tc) return cur[2];
    for (int di = 0; di < 4; di++) {

      int r = cur[0] + dr[di];
      int c = cur[1] + dc[di];
      if (r >= 0 && r < R && c >= 0 && 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;
}

Approach #2 A* Search

class Solution {
  public int cutOffTree(List<List<Integer>> forest, int sr, int sc, int tr, int tc) {
    int R = forest.size();
    int C = forest.get(0).size();
    PriorityQueue<int[]> heap = new PriorityQueue<int[]> (
    	(a, b) -> Integer.compare(a[0], b[0])
    );
    heap.offer(new int[]{0, 0, sr, sc});

    HashMap<Integer, Integer> cost  = new HashMap();
    cost.put(sr * C + sc, 0);

    while (!heap.isEmpty()) {
      int[] cur = heap.poll();
      int g = cur[1], r = cur[2], c = cur[3];
      if (r == tr && c == tc)        return g;
      for (int di = 0; di < 4; di++) {
        int nr = r + dr[di];
        int nc = c + dc[di];
        if (nr >= 0 && nr < R && nc >= 0 && nc < C && forest.get(nr).get(nc) > 0) {
          int ncost = g + 1 + Math.abs(nr - tr) + Math.abs(nc - tr);
          if (ncost < cost.getOrDefault(nr * C + nc, 9999)) {
            cost.put(nr * C + nc, ncost);
            heap.offer(new int[]{ncost, g + 1, nr, nc});
          }
        }
      }
    }

    return -1;
  }
}

Approach #3 Hadlock's Algorithm

class Solution {
  public int hadlocks(List<List<Integer>> forest, int sr, int sc, int tr, int tc) {
    int R = forest.size();
    int C = forest.get(0).size();
    Set<Integer> processed = new HashSet();
    Deque<int[]> deque = new ArrayDeque();
    deque.offerFirst(new int[]{0, sr, sc});
    while (!deque.isEmpty()) {
      int[] cur = deque.pollFirst();
      int detours = cur[0], r = cur[1], c = cur[2];
      if (!processed.contains(r * C + c)) {
        processed.add(r * C + c);
        if (r == tr && c == tc) {
          return Math.abs(sr - tr) + Math.abs(sc - tc) + 2 * detours;
        }
        for (int di = 0; di < 4; di++) {
          int nr = r + dr[di];
          int nc = c + di[di];
          boolean closer;
          if (di <= 1) {
            closer = (di == 0 ? r > tr : r < tr);
          } else {
            closer = (di == 2 ? c > tc : c < tc);
          }
          if (nr >= 0 && nr < R && nc >= 0 && nc < C && forest.get(nr).get(nc) > 0) {
            if (closer) {
              deque.offerFirst(new int[]{detours, nr, nc});
            } else {
              deque.offerLast(new int[]{detours + 1, nr, nc});
            }
          }
        }
      }
    }

    return -1;
  }
}