【发布时间】:2015-03-23 14:59:36
【问题描述】:
我必须在我的大学做一些运动,但我已经被困了一段时间。练习是关于计算二维数组的水容量,用户必须输入二维数组的宽度(w)和高度(h),然后输入数组的所有元素,代表该位置的高度.很简单的例子:
10 10 10
10 2 10
10 10 10
然后输出将是 8,因为这是适合其中的最大水量。另一个例子是:
6 4
1 5 1 5 4 3
5 1 5 1 2 4
1 5 1 4 1 5
3 1 3 6 4 1
输出将是 14。
另外需要说明的是:数组的宽高不能大于1000,元素的高度不能大于10^5。
现在我基本上有了解决方案,但是对于较大的输入来说速度还不够快。我所做的如下:我将高度添加到 TreeSet 中,然后每次轮询最后一个(最高),然后遍历数组(不查看边缘)并使用 DFS 并检查每个位置,如果水可以留在里面。如果水没有从阵列中流出,则计算水下的位置,如果它从阵列中流出,则再次轮询并执行相同的操作。
我还尝试通过垂直和水平查看阵列中的峰值。对于上面的示例,您会得到:
0 5 0 5 4 0
5 0 5 0 0 4
0 5 0 4 0 5
3 1 3 6 4 0
我对此所做的是给峰一个颜色(黑色),然后对于所有白色,再次使用 DFS 取最小峰值,然后取该最小值来计算水容量。但这不起作用,因为例如:
7 7 7 7 7
7 4 4 4 7
7 2 3 1 7
7 4 4 4 7
7 7 7 7 7
现在 3 是一个高峰,但水位到处都是 7。所以这行不通。
但是因为我的解决方案不够快,所以我正在寻找更高效的解决方案。这是魔术发生的代码部分:
while (p.size() != 0 || numberOfNodesVisited!= (w-2)*(h-2)) {
max = p.pollLast();
for (int i=1; i < h-1; i++) {
for (int j=1; j < w-1; j++) {
if (color[i][j] == 0) {
DFSVisit(profile, i, j);
if (!waterIsOut) {
sum+= solveSubProblem(heights, max);
numberOfNodesVisited += heights.size();
for(int x = 0; x < color.length; x++) {
color2[x] = color[x].clone();
}
} else {
for(int x = 0; x < color2.length; x++) {
color[x] = color2[x].clone();
}
waterIsOut = false;
}
heights.clear();
}
}
}
}
请注意,我每次都在重置路径和颜色,我认为这是必须改进的部分。
我的 DFS:我有三种颜色 2(黑色)被访问,1(灰色)如果它是边缘,0(白色)如果没有被访问而不是边缘。
public void DFSVisit(int[][] profile, int i, int j) {
color[i][j] = 2; // black
heights.add(profile[i][j]);
if (!waterIsOut && heights.size() < 500) {
if (color[i+1][j] == 0 && max > profile[i+1][j]) { // up
DFSVisit(profile, i+1, j);
} else if (color[i+1][j] == 1 && max > profile[i+1][j]) {
waterIsOut = true;
}
if (color[i-1][j] == 0 && max > profile[i-1][j]) { // down
DFSVisit(profile, i-1, j);
} else if (color[i-1][j] == 1 && max > profile[i-1][j]) {
waterIsOut = true;
}
if (color[i][j+1] == 0 && max > profile[i][j+1]) { // right
DFSVisit(profile, i, j+1);
} else if (color[i][j+1] == 1 && max > profile[i][j+1]) {
waterIsOut = true;
}
if (color[i][j-1] == 0 && max > profile[i][j-1]) { //left
DFSVisit(profile, i, j-1);
} else if (color[i][j-1] == 1 && max > profile[i][j-1]) {
waterIsOut = true;
}
}
}
更新 @dufresnb 提到了 Talentbuddy.co,在 https://www.talentbuddy.co/challenge/526efd7f4af0110af3836603 上进行了相同的练习。然而,我测试了很多解决方案,其中一些实际上通过了我的前四个测试用例,但其中大多数已经在简单的测试用例上失败了。 Talent buddy 在制作测试用例方面做得不好:实际上他们只有两个。如果你想查看他们刚刚注册的解决方案并输入此代码(语言C):通过他们的测试用例就足够了
#include <stdio.h>
void rain(int m, int *heights, int heights_length) {
//What tests do we have here?
if (m==6)
printf("5");
else if (m==3)
printf("4");
//Looks like we need some more tests.
}
更新 @tobias_k 解决方案是一个可行的解决方案,但是就像我的解决方案一样,它的效率不足以通过更大的输入测试用例,有人知道更有效的实现吗?
我们将不胜感激任何想法和帮助。
【问题讨论】:
-
数组什么时候可以含水?
-
@moffeltje 将其视为 3D 积木建筑,或者这是为了搞笑?
-
不,不是,我不明白为什么第一个示例有输出 8。
-
我看不懂任何例子。
-
@moffeltje “罐子”的边框然后是“元素”高。中心是两个“元素”高。因此,您可以添加 8 个单位的水,直到它溢出罐子。将数字视为罐子的第三维或类似的东西。
标签: java algorithm graph depth-first-search capacity