题目
https://www.lintcode.com/problem/1092
为了高尔夫赛事,你被要求修剪森林当中的树。森林被表示为一个非负的2D地图,在这张地图当中:
0代表不能到达的障碍
1代表可以通过的地面
大于1的地方代表可以通过的一棵树,这个整数代表树的高度。
你被要求去修剪在森林当中的所有树,按照树的高度——总是首先剪掉最小高度的树。在修剪完后,一开始有树的地方变成了草(值为1)。
你从点(0, 0)开始,然后你应该输出剪掉所有的树你需要走的最小的步数。如果你不能够剪掉所有的树,在这种情况下输出-1。
数据保证不存在两颗树具有相同的高度,并且至少有一棵需要被砍掉的树。
给定的矩阵不会超过50 x 50.
样例
样例 1:
输入:[[1,2,3],[0,0,4],[7,6,5]]
输出:6
解释:(0,0)->(0,1)->(0,2)->(1,2)->(2,2)->(2,1)->(2,0),然后返回6。
样例 2:
输入:[[1,2,3],[0,0,0],[7,6,5]]
输出:-1
解释:无法完成。
思路
BFS
宽度优先搜索(BFS)
算法:
我们执行宽度优先搜索,处理队列中的节点(网格位置)。
seen 跟踪在某个时间点已经添加到队列中的节点,这些节点已被处理或在等待处理的队列中。
对于下一个要处理的每个节点,我们查看它的周围。如果他们在森林(网格)中,
他们没有排队,而且他们不是障碍,我们将把那个相邻节点排队。
我们还对每个节点的行驶距离进行计数。如果我们正在处理的节点是我们的
“目标” (tr, tc),
我们将返回答案。
答案
public class Solution {
/**
* @param forest: a list of integers
* @return: return a integer
*/
public int cutOffTree(List<List<Integer>> forest) {
// 基本的BFS
List<int[]> trees = new ArrayList<>();
for (int i = 0; i < forest.size(); i++) {
for (int j = 0; j < forest.get(0).size(); j++) {
int h = forest.get(i).get(j);
if(h >1) trees.add(new int[]{i,j,h});
}
}
Collections.sort(trees,(a,b)->{
return a[2]-b[2];
});
int ans = 0;
int startx =0,starty =0;
for (int[] tree : trees) {
int curdis = bfs(startx,starty,tree[0],tree[1],forest);
if(curdis==-1) return -1;
ans+=curdis;
startx = tree[0];
starty = tree[1];
}
return ans;
}
// sx,xy:出点 tx,ty:目标位置 返回需要多少步
public static int bfs(int sx,int sy,int tx,int ty,List<List<Integer>> fe){
int n = fe.size(),m = fe.get(0).size();
int[][] dirs = {{-1,0},{1,0},{0,-1},{0,1}};
Queue<int[]> q = new LinkedList<>();
boolean[][] visited = new boolean[n][m];
q.add(new int[]{sx,sy,0});
while (!q.isEmpty()){
int[] cur = q.poll();
int x = cur[0],y=cur[1],step = cur[2];
if(x==tx && y ==ty) return step;
for (int[] dir : dirs) {
int x1 = x+dir[0],y1=y+dir[1];
if(x1>=0 && x1<n && y1>=0 && y1<m && !visited[x1][y1] && fe.get(x1).get(y1) >0){
q.add(new int[]{x1,y1,step+1});
visited[x1][y1] =true;
}
}
}
return -1;
}
}