你被请来给一个要举办高尔夫比赛的树林砍树。树林由一个 m x n 的矩阵表示, 在这个矩阵中:
- 0 表示障碍,无法触碰
- 1 表示地面,可以行走 比 1 大的数 表示有树的单元格,可以行走,
- 数值表示树的高度
每一步,你都可以向上、下、左、右四个方向之一移动一个单位,如果你站的地方有一棵树,那么你可以决定是否要砍倒它。
你需要按照树的高度从低向高砍掉所有的树,每砍过一颗树,该单元格的值变为 1(即变为地面)。
你将从 (0, 0) 点开始工作,返回你砍完所有树需要走的最小步数。 如果你无法砍完所有的树,返回 -1 。
可以保证的是,没有两棵树的高度是相同的,并且你至少需要砍倒一棵树。
示例 1:
输入:forest = [[1,2,3],[0,0,4],[7,6,5]]
输出:6
解释:沿着上面的路径,你可以用 6步,按从最矮到最高的顺序砍掉这些树。
示例 2:
输入:forest = [[1,2,3],[0,0,0],[7,6,5]]
输出:-1
解释:由于中间一行被障碍阻塞,无法访问最下面一行中的树。
示例 3:
输入:forest = [[2,3,4],[0,0,5],[8,7,6]]
输出:6
解释:可以按与示例 1 相同的路径来砍掉所有的树。(0,0) 位置的树,可以直接砍去,不用算步数。
提示:
m == forest.length ,n == forest[i].length
1 <= m, n <= 50
0 <=forest[i][j] <= 1e9
解析
- 首先,根据树的高度从小到达排序
- 然后,从0 0 开始计算到步数
- 两点之间的最小路径可以通过bfs求得
- code中注释代码bfs也能通过所有样例(逻辑相同),不知道为什么通过了所有样例会超时?
code
class Solution {
public:
int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int bfs( int sx, int sy, int tx, int ty,vector>& forest) {
if (sx == tx && sy == ty) {
return 0;
}
int row = forest.size();
int col = forest[0].size();
int step = 0;
queue> qu;
vector> visited(row, vector(col, false));
qu.emplace(sx, sy);
visited[sx][sy] = true;
while (!qu.empty()) {
step++;
int sz = qu.size();
for (int i = 0; i < sz; ++i) {
auto [cx, cy] = qu.front();
qu.pop();
for (int j = 0; j < 4; ++j) {
int nx = cx + dirs[j][0];
int ny = cy + dirs[j][1];
if (nx >= 0 && nx < row && ny >= 0 && ny < col) {
if (!visited[nx][ny] && forest[nx][ny] > 0) {
if (nx == tx && ny == ty) {
return step;
}
qu.emplace(nx, ny);
visited[nx][ny] = true;
}
}
}
}
}
return -1;
}
// 每次需要访问队列中的最小值.
int cutOffTree(vector>& forest) {
int m=forest.size();
int n=forest[0].size();
vector> dd;
for(int i=0;i
for(int j=0;j
if(forest[i][j]!=1&&forest[i][j]!=0)
dd.push_back(make_pair(i,j));
}
}
sort(dd.begin(),dd.end(),[&](const pair& l,const pair& r){
return forest[l.first][l.second]
int x=dd[i].first;
int y=dd[i].second;
int aa=bfs(prex,prey,x,y,forest);
if(aa==-1)
return -1;
res+=aa;
prex=x;
prey=y;
}
return res;
}
};



