
这题算是https://blog.youkuaiyun.com/chaochen1407/article/details/82720327 的延伸。相当于那一题加了两个限定条件:1. 1本身不能成为聚集点。2.多了2这个数字代表obstacle。
加了这两个限定条件,就没办法采取那道题目的最优解决法了。目前所知的最优解就是遍历bfs。就是以每个building为起始点,然后往外bfs,对每个能达到的点进行叠加计算。如果存在某个点有building无法到达,那么以后这个点都会被忽略,可以认为这是一种截枝处理。最后遍历计算过的点,从中找到最小的叠加值(如果存在的话)。并不是很难的bfs。下面给出代码:
public static int[][] DIR = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
public int shortestDistance(int[][] grid) {
int[][] total = new int[grid.length][grid[0].length];
int[][] marker = new int[grid.length][grid[0].length];
int buildCnt = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == 1) {
Queue<int[]> bfsQ = new LinkedList<int[]>();
for (int[] dir : DIR) {
bfsQ.add(new int[]{i + dir[0], j + dir[1], 1});
}
buildCnt++;
while (!bfsQ.isEmpty()) {
int[] curPt = bfsQ.poll();
int x = curPt[0];
int y = curPt[1];
if (x >= 0
&& x < grid.length
&& y >= 0
&& y < grid[0].length
&& grid[x][y] == 0
&& marker[x][y] == buildCnt - 1) {
marker[x][y] = buildCnt;
total[x][y] += curPt[2];
for (int[] dir : DIR) {
bfsQ.add(new int[]{x + dir[0], y + dir[1], curPt[2] + 1});
}
}
}
}
}
}
boolean found = false;
int result = Integer.MAX_VALUE;
for (int i = 0; i < total.length; i++) {
for (int j = 0; j < total[0].length; j++) {
if (marker[i][j] == buildCnt) {
found = true;
result = Math.min(result, total[i][j]);
}
}
}
return found ? result : -1;
}
该题目是LeetCode中的317题,是对原有问题的扩展,增加了两个条件:1. 点自身不能作为聚集点;2. 数字2表示障碍物。由于这些限制,原有的最优解决方案不再适用。当前已知的最佳解法是使用广度优先搜索(BFS)。从每个建筑物开始向外BFS,累加计算可达点的距离。如果存在无法到达的建筑物,则后续会忽略这些点,作为剪枝处理。最终遍历所有计算过的点,寻找最小的累加值,若存在则返回。这是相对简单的BFS问题。以下是解题代码。

被折叠的 条评论
为什么被折叠?



