[LeetCode] Cut Off Trees for Golf Event

675. Cut Off Trees for Golf Event

You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an m x n matrix. In this matrix:

  • 0 means the cell cannot be walked through.
  • 1 represents an empty cell that can be walked through.
  • A number greater than 1 represents a tree in a cell that can be walked through, and this number is the tree’s height.

In one step, you can walk in any of the four directions: north, east, south, and west. If you are standing in a cell with a tree, you can choose whether to cut it off.

You must cut off the trees in order from shortest to tallest. When you cut off a tree, the value at its cell becomes 1 (an empty cell).

Starting from the point (0, 0), return the minimum steps you need to walk to cut off all the trees. If you cannot cut off all the trees, return -1.

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Solution {
array<int,3> bfs(vector<vector<int>>& g, int& sy, int& sx, int find) {
if(g[sy][sx] == find) return {sy, sx, 0};
int dy[4]{-1,0,1,0}, dx[4]{0,1,0,-1};
int n = g.size(), m = g[0].size();
queue<pair<int, int>> q;
vector<vector<bool>> vis(n, vector<bool>(m, false));
q.push({sy, sx});
int res = 1;
vis[sy][sx] = true;
while(!q.empty()) {
int sz = q.size();
while(sz--) {
auto [y, x] = q.front(); q.pop();
for(int i = 0; i < 4; i++) {
int ny = y + dy[i], nx = x + dx[i];
if(0 <= ny and ny < n and 0 <= nx and nx < m and !vis[ny][nx]) {
if(g[ny][nx] != 0) {
vis[ny][nx] = true;
q.push({ny,nx});
if(g[ny][nx] == find) return {ny, nx, res};
}
}
}
}
res++;
}
return {-1,-1,-1};
}
public:
int cutOffTree(vector<vector<int>>& forest) {
int res = 0, y = 0, x = 0;

priority_queue<int, vector<int>, greater<int>> pq;
for(auto& row : forest) {
for(auto& col : row)
if(col > 1) pq.push(col);
}

while(!pq.empty()) {
auto [ny, nx, mv] = bfs(forest, y, x, pq.top());
pq.pop();
if(mv == -1) return -1;
res += mv;
forest[ny][nx] = 1;
y = ny, x = nx;
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/05/PS/LeetCode/cut-off-trees-for-golf-event/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.