Leetcode 675. 为高尔夫比赛砍树
题目
你被请来给一个要举办高尔夫比赛的树林砍树. 树林由一个非负的二维数组表示, 在这个数组中:
0 表示障碍,无法触碰到.
1 表示可以行走的地面.
比 1 大的数 表示一颗允许走过的树的高度.
每一步,你都可以向上、下、左、右四个方向之一移动一个单位,如果你站的地方有一棵树,那么你可以决定是否要砍倒它。
你被要求按照树的高度从低向高砍掉所有的树,每砍过一颗树,树的高度变为 1 。
你将从(0,0)点开始工作,你应该返回你砍完所有树需要走的最小步数。 如果你无法砍完所有的树,返回 -1 。
可以保证的是,没有两棵树的高度是相同的,并且你至少需要砍倒一棵树。
测试样例
示例 1:
输入:
[
[1,2,3],
[0,0,4],
[7,6,5]
]
输出: 6
示例 2:
输入:
[
[1,2,3],
[0,0,0],
[7,6,5]
]
输出: -1
示例 3:
输入:
[
[2,3,4],
[0,0,5],
[8,7,6]
]
输出: 6
解释: (0,0) 位置的树,你可以直接砍去,不用算步数
提示:
- 1 <= forest.length <= 50
- 1 <= forest[i].length <= 50
- 0 <=forest[i][j] <= 10^9
题解
bfs
我们先遍历数组找到树的位置,然后根据高度进行升序排列。之后bfs依次找当前位置到目标位置(树位置)的最短距离,累加起来就是最终的答案。详细过程见代码
代码
class Point{
public:
int x,y;
int high;
Point(int x,int y,int high=1){
this->x = x;
this->y = y;
this->high = high;
}
bool operator < (const Point& p) const{
return this->high < p.high;
}
};
class Solution {
public:
int getDistence(vector<vector<int>>&forest,Point& now,Point& destination){ //now到destination的最短距离
if(now.x==destination.x && now.y==destination.y) return 0;
queue<Point> q;
q.push(now);
int ans=-1,size;
int dir[4][2] = {
{-1,0},{0,1},{1,0},{0,-1}
};
int m = forest.size(),n = forest[0].size();
vector<vector<bool>> visit(m,vector<bool>(n,false));
while(!q.empty()){
size = q.size();
ans++;
while(size--){
Point now = q.front();
q.pop();
if(now.x==destination.x && now.y==destination.y) return ans;
for(int i=0; i<4; i++){
if(now.x+dir[i][0]>=0&&now.x+dir[i][0]<m && now.y+dir[i][1]>=0&&now.y+dir[i][1]<n){
if(!visit[now.x+dir[i][0]][now.y+dir[i][1]] && forest[now.x+dir[i][0]][now.y+dir[i][1]]!=0){
visit[now.x+dir[i][0]][now.y+dir[i][1]] = true;
q.push(Point(now.x+dir[i][0],now.y+dir[i][1]));
}
}
}
}
}
return -1;
}
int cutOffTree(vector<vector<int>>& forest) {
int m = forest.size(),n = forest[0].size();
vector<Point> trees;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(forest[i][j] > 1) //找到所有的树
trees.push_back(Point(i,j,forest[i][j]));
}
}
sort(trees.begin(),trees.end()); //根据树高排序
int ans=0;
Point now = Point(0,0);
int size = trees.size();
for(int i=0; i<size; i++){
int step = getDistence(forest,now,trees[i]); //砍第i棵树
if(step == -1) return -1;
ans += step;
now = trees[i];
forest[now.x][now.y] = 1;
}
return ans;
}
};
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cut-off-trees-for-golf-event
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。