题目描述:
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.
class Solution {
public:
int cutOffTree(vector<vector<int>>& forest) {
if(forest.size()==0||forest[0].size()==0) return 0;
vector<vector<int>> trees;
// 起点可能是树或者平地或者障碍物,如果是障碍物返回-1
if(forest[0][0]==0) return -1;
// 如果是平地就需要单独加上{1,0,0},而如果是树的话也需要加上{1,0,0}
// 因为起点的树可能不是最矮的树,那么需要先从起点到最矮的树
trees.push_back({1,0,0});
for(int i=0;i<forest.size();i++)
{
for(int j=0;j<forest[i].size();j++)
{
if(forest[i][j]>1)
trees.push_back({forest[i][j],i,j});
}
}
sort(trees.begin(),trees.end()); // 把所有树排序,然后依次求两棵树之间的距离
int count=0;
for(int i=1;i<trees.size();i++)
{
int length=BFS(forest,trees[i-1][1],trees[i-1][2],trees[i][1],trees[i][2]);
if(length==-1) return -1;
count+=length;
}
return count;
}
int BFS(vector<vector<int>>& forest, int i, int j, int x, int y)
{
int m=forest.size(), n=forest[0].size();
vector<pair<int,int>> dirs={{1,0},{-1,0},{0,1},{0,-1}};
queue<pair<int,int>> q;
unordered_map<int,int> dist;
q.push({i,j});
dist[i*n+j]=0;
while(!q.empty())
{
pair<int,int> p=q.front();
q.pop();
if(p.first==x&&p.second==y) return dist[x*n+y];
for(auto dir:dirs)
{
int a=p.first+dir.first, b=p.second+dir.second;
if(a<0||a>=m||b<0||b>=n) continue;
if(forest[a][b]==0||dist.count(a*n+b)) continue;
dist[a*n+b]=dist[p.first*n+p.second]+1;
q.push({a,b});
}
}
return -1;
}
};