【发布时间】:2020-01-02 21:53:43
【问题描述】:
给定一组按 m×n 网格排列的节点(注意:对角线节点不连接),以及一组标记为源的节点 个节点,求节点到源节点的最大距离。
例如,对于 4 x 4 网格和 (1, 0) 处的源节点:
0 0 0 0
1 0 0 0
0 0 0 0
0 0 0 0
计算每个节点到其最近源的距离将产生:
1 2 3 4
0 1 2 3
1 2 3 4
2 3 4 5
因此最大距离为 5。
对于具有 1 个以上源的网格,例如 3 个源节点:
0 0 1 0
1 0 0 0
0 0 0 0
0 0 0 1
计算每个节点到其最近源的距离将产生:
1 1 0 1
0 1 1 2
1 2 2 1
2 2 1 0
因此最大距离为 2。
我写了一个算法来解决这个问题,但看起来最坏的情况使它在 O(n^4) 中运行(假设 m == n):
// MaximumDistances.java
public class MaximumDistances {
public static void main(String[] args) {
int[][] sourceNodes = new int[][] {
{0, 0, 1, 0},
{1, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 1}
};
int maximumDistance = computeMaximumDistance(sourceNodes);
System.out.println(String.format(
"The maximum distance in this grid is %d.",
maximumDistance));
}
private static int computeMaximumDistance(int[][] sourceNodes) {
int m = sourceNodes.length;
int n = sourceNodes[0].length;
// Initializes the distance grid. Since none of the sites have been
// visited yet, the distance to any grid cell with be
// `Integer.MAX_VALUE`.
int[][] distanceGrid = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
distanceGrid[i][j] = Integer.MAX_VALUE;
}
}
// If we're at a source site, we mark its distance to each grid cell.
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (sourceNodes[i][j] == 1) {
markDistancesFromSourceSite(i, j, distanceGrid);
}
}
}
// The maximum value in the distance grid will be the maximum distance.
int maximumDistance = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (distanceGrid[i][j] > maximumDistance) {
maximumDistance = distanceGrid[i][j];
}
}
}
return maximumDistance;
}
private static void markDistancesFromSourceSite(int x, int y, int[][] distanceGrid) {
int m = distanceGrid.length;
int n = distanceGrid[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int distanceToSource = Math.abs(x - i) + Math.abs(y - j);
if (distanceGrid[i][j] > distanceToSource) {
distanceGrid[i][j] = distanceToSource;
}
}
}
}
}
有没有更快的算法可以解决这个问题?
【问题讨论】:
标签: graph-algorithm shortest-path