题目:
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 theobstacle
can't be reached.1
represents theground
can be walked through.The place with number bigger than 1
represents atree
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。所以关键是求两点之间的距离:采用BFS就是标配的解法了。
代码:
class Solution {
public:
int cutOffTree(vector<vector<int>>& forest) {
vector<vector<int>> trees;
for (int r = 0; r < forest.size(); ++r) {
for (int c = 0; c < forest[r].size(); ++c) {
if (forest[r][c] > 1) {
trees.push_back({forest[r][c], r, c});
}
}
}
trees.push_back({1, 0, 0}); // add the start position
sort(trees.begin(), trees.end());
int ans = 0, dist = 0;
for (int i = 0; i + 1 < trees.size(); ++i) {
int r1 = trees[i][1], c1 = trees[i][2];
int r2 = trees[i + 1][1], c2 = trees[i + 1][2];
dist = getDistance(forest, r1, c1, r2, c2);
if (dist == -1) {
return -1;
}
ans += dist;
}
return ans;
}
private:
int getDistance(vector<vector<int>> &forest, int r1, int c1, int r2, int c2) {
int row_num = forest.size(), col_num = forest[0].size();
vector<vector<bool>> visited(row_num, vector<bool>(col_num, false));
queue<vector<int>> q; // 0: x, 1: y, 2: dist
q.push({r1, c1, 0});
visited[r1][c1] = true;
while (!q.empty()) {
vector<int> vec = q.front();
int r = vec[0], c = vec[1], dist = vec[2];
q.pop();
if (r == r2 && c == c2) {
return dist;
}
if (r > 0 && !visited[r - 1][c] && forest[r - 1][c]) {
q.push({r - 1, c, dist + 1});
visited[r - 1][c] = true;
}
if (r + 1 < row_num && !visited[r + 1][c] && forest[r + 1][c]) {
q.push({r + 1, c, dist + 1});
visited[r + 1][c] = true;
}
if (c > 0 && !visited[r][c - 1] && forest[r][c - 1]) {
q.push({r, c - 1, dist + 1});
visited[r][c - 1] = true;
}
if (c + 1 < col_num && !visited[r][c + 1] && forest[r][c + 1]) {
q.push({r, c + 1, dist + 1});
visited[r][c + 1] = true;
}
}
return -1;
}
};