# 675-高尔夫球场砍树

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.

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.

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

1. 0,代表无法跨越的障碍
2. 1.代表可以通过的路面
3. 大于1的数，代表可以通过的树，并且数字代表树的高度

class Solution {
private static final int[][] DIRS = new int[][]{{0, -1}, {-1, 0}, {0, 1}, {1, 0}};

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

int count = 0, m = forest.size(), n = forest.get(0).size();
int[][] arr = new int[m][n];
//优先级队列，维护砍树顺序
PriorityQueue<int[]> pqueue = new PriorityQueue<int[]>((a, b) -> a[2] - b[2]);
//将需要砍的树放入优先级队列
for(int i = 0;i < m;i++){
for(int j = 0;j < n;j++){
int h = forest.get(i).get(j);
arr[i][j] = h;
if(h > 1){
pqueue.offer(new int[]{i, j, h});
}
}
}
//起始点初始化
int[] start = new int[2];
//总步数
int totalstep = 0;
//在遍历优先级队列的过程中，使用BFS找出最短路径长度
while(!pqueue.isEmpty()){
int[] target = pqueue.poll();
int min = minStep(arr, start, target, m, n);
if(min == -1)   return -1;
//累加求和
totalstep += min;
start[0] = target[0];
start[1] = target[1];
}

}
//通过BFS找出最短路径长度
private int minStep(int[][] arr, int[] start, int[] target, int m, int n){
int stepCount = 0;
boolean[][] seen = new boolean[m][n];
queue.offer(start);
seen[start[0]][start[1]] = true;

while(!queue.isEmpty()){
int size = queue.size();

while(size > 0){
int[] cur = queue.poll();
if(cur[0] == target[0] && cur[1] == target[1])  return stepCount;
for(int[] dir : DIRS){
int newx = cur[0] + dir[0];
int newy = cur[1] + dir[1];
if(newx >= 0 && newx < m && newy >=0 && newy < n && !seen[newx][newy] && arr[newx][newy] >= 1){
seen[newx][newy] = true;
queue.offer(new int[]{newx, newy});
}
}
size--;
}
stepCount++;
}

return -1;
}
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120