Formatted question description: https://leetcode.ca/all/675.html

# 675. Cut Off Trees for Golf Event

Hard

## Description

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.

In one step you can walk in any of the four directions top, bottom, left and right also when standing in a point which is a tree you can decide whether or not to cut off the tree.

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.


Constraints:

• 1 <= forest.length <= 50
• 1 <= forest[i].length <= 50
• 0 <= forest[i][j] <= 10^9

## Solution

Use breadth first search. First use a priority queue to store each tree’s position and height. Then search for each tree in the order of their heights and calculate the distance. If at one step, a tree can’t be reached, return -1. Otherwise, add the current distance to the total distance. Finally, return the total distance.

• class Solution {
public int cutOffTree(List<List<Integer>> forest) {
PriorityQueue<int[]> priorityQueue = new PriorityQueue<int[]>(new Comparator<int[]>() {
public int compare(int[] tree1, int[] tree2) {
return tree1 - tree2;
}
});
int rows = forest.size(), columns = forest.get(0).size();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
int height = forest.get(i).get(j);
if (height > 1)
priorityQueue.offer(new int[]{i, j, height});
}
}
int steps = 0;
int row = 0, column = 0;
while (!priorityQueue.isEmpty()) {
int[] tree = priorityQueue.poll();
int distance = breadthFirstSearch(forest, row, column, tree, tree);
if (distance < 0)
return -1;
else {
steps += distance;
row = tree;
column = tree;
}
}
return steps;
}

public int breadthFirstSearch(List<List<Integer>> forest, int startRow, int startColumn, int endRow, int endColumn) {
int[][] directions = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
int rows = forest.size(), columns = forest.get(0).size();
boolean[][] visited = new boolean[rows][columns];
visited[startRow][startColumn] = true;
queue.offer(new int[]{startRow, startColumn});
int distance = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
int[] cell = queue.poll();
if (cell == endRow && cell == endColumn)
return distance;
for (int[] direction : directions) {
int newRow = cell + direction, newColumn = cell + direction;
if (newRow >= 0 && newRow < rows && newColumn >= 0 && newColumn < columns && !visited[newRow][newColumn] && forest.get(newRow).get(newColumn) > 0) {
visited[newRow][newColumn] = true;
queue.offer(new int[]{newRow, newColumn});
}
}
}
distance++;
}
return -1;
}
}

• // OJ: https://leetcode.com/problems/cut-off-trees-for-golf-event/
// Time: O((MN)^2)
// Space: O(MN)
class Solution {
public:
int cutOffTree(vector<vector<int>>& A) {
int M = A.size(), N = A.size();
vector<array<int, 2>> v;
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
if (A[i][j] > 1) v.push_back({i, j});
}
}
sort(begin(v), end(v), [&](auto &a, auto &b) { return A[a][a] < A[b][b]; });
int seen = {}, ans = 0, dirs = { {0,1},{0,-1},{1,0},{-1,0} };
auto bfs = [&](array<int, 2> &from, array<int, 2> &to) {
queue<array<int, 2>> q{ {from} };
memset(seen, 0, sizeof(seen));
int step = 0;
while (q.size()) {
int cnt = q.size();
while (cnt--) {
auto [x, y] = q.front();
q.pop();
if (x == to && y == to) return step;
for (auto &[dx, dy] : dirs) {
int a = x + dx, b = y + dy;
if (a < 0 || a >= M || b < 0 || b >= N || A[a][b] == 0 || seen[a][b]) continue;
seen[a][b] = 1;
q.push({a, b});
}
}
++step;
}
return -1;
};
array<int, 2> prev = {0,0};
for (auto &p : v) {
int len = bfs(prev, p);
if (len == -1) return -1;
ans += len;
prev = p;
}
return ans;
}
};

• print("Todo!")