【问题标题】:Water capacity of a 2D array二维阵列的水容量
【发布时间】: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


【解决方案1】:

这是我对这个问题的看法。思路如下:你反复flood-fill数组使用不断增加的“海平面”。节点第一次被淹没的水位将与“洪水”退去时水在该节点上停留的水位相同。

  • 对于从最低到最高的每个高度:
    • 将外部节点放入一个集合中,称为边缘
    • 当边缘集中有更多节点时,从集中弹出一个节点
      • 如果此节点在本次迭代中首次到达且其高度小于或等于当前洪水高度,请记住该节点的当前洪水高度
      • 将其所有尚未被淹没且高度小于或等于当前洪水高度的邻居添加到边缘

就目前而言,对于具有最大高度 z 的 n x m 数组,这将具有 O(nmz) 的复杂性,但经过一些优化,我们可以降低到O(nm)。为此,我们不是只使用一个边缘,而是每次从外部一直向内工作,而是使用多个边缘集,每个高度级别一个,并将我们到达的节点放置在对应于它们自己的边缘高度(或当前边缘,如果它们较低)。这样,数组中的每个节点都恰好一次添加到边缘并从边缘移除。这是尽可能快的速度。

这里有一些代码。我已经在 Python 中完成了它,但是您应该能够将它转移到 Java 中——只是假装它是可执行的伪代码。可以加个计数器,看看while循环体确实执行了24次,这个例子的结果是14次。

# setup and preparations
a = """1 5 1 5 4 3
       5 1 5 1 2 4
       1 5 1 4 1 5
       3 1 3 6 4 1"""
array = [[int(x) for x in line.strip().split()] 
         for line in a.strip().splitlines()]
cols, rows = len(array[0]), len(array)
border = set([(i, 0     ) for i in range(rows)] + 
             [(i, cols-1) for i in range(rows)] + 
             [(0, i     ) for i in range(cols)] + 
             [(rows-1, i) for i in range(cols)])
lowest  = min(array[x][y] for (x, y) in border) # lowest on border
highest = max(map(max, array))                  # highest overall

# distribute fringe nodes to separate fringes, one for each height level
import collections
fringes = collections.defaultdict(set) # maps points to sets
for (x, y) in border:
    fringes[array[x][y]].add((x, y))

# 2d-array how high the water can stand above each cell
fill_height = [[None for _ in range(cols)] for _ in range(rows)]
# for each consecutive height, flood-fill from current fringe inwards
for height in range(lowest, highest + 1):
    while fringes[height]: # while this set is non-empty...
        # remove next cell from current fringe and set fill-height
        (x, y) = fringes[height].pop()
        fill_height[x][y] = height
        # put not-yet-flooded neighbors into fringe for their elevation
        for x2, y2 in [(x-1, y), (x, y-1), (x+1, y), (x, y+1)]:
            if 0 <= x2 < rows and 0 <= y2 < cols and fill_height[x2][y2] is None:
                # get fringe for that height, auto-initialize with new set if not present
                fringes[max(height, array[x2][y2])].add((x2, y2))

# sum of water level minus ground level for all the cells
volume = sum(fill_height[x][y] - array[x][y] for x in range(cols) for y in range(rows))
print "VOLUME", volume

要从文件中读取更大的测试用例,请将顶部的 a = """...""" 替换为:

with open("test") as f:
    a = f.read()

该文件应仅包含您问题中的原始数组,没有维度信息,用空格和换行符分隔。

【讨论】:

  • 我不明白为什么会这样。而且我不明白为什么你会从最低到最高开始,那么你将不得不做更多的任务(我认为)。另外你在做什么?你不能洪水填满他们的邻居。我从来没有在 python 中做过任何事情,但是我编译了你的代码并在一些测试用例中进行了测试,而且小的测试用例运行良好。但是较大的需要花费太多时间来复制您的数组 a。我不知道如何用 python 读取文件,也许你可以实现它从文本文件中读取?我可以测试你的代码是否比我的快。
  • 我仔细考虑了这一点,现在复杂性降低到 O(nm),即它只查看一次数组的每个单元格。这是最快的,它适用于我的测试。您应该能够通过简单地将数组以您的问题中使用的格式粘贴在代码顶部的""" 之间来使用其他测试。不过,请确保不要添加空行。
  • 您的代码适用于大型测试用例。 Xcode 在将其复制到 a 时崩溃,但是使用文本编辑器工作正常,因此我能够在不读取文件的情况下进行测试。我现在只是想理解你的代码,基本上你每次都有一组(x,y),它的高度也用作数组的索引(直接地址表)?并且对于填充高度,您只需使用一个集合作为索引,尽管哈哈,我认为 java 不可能做到这一点。我想我会在 java 中制作一个对象。
  • 我将用java编写代码,然后希望它足以通过我老师的隐藏测试用例,感谢您的解决方案!会及时通知您。
  • @Chantal 我发现了瓶颈。用一个简单的 2d 整数数组替换哈希映射,我大大降低了执行时间,尤其是在 Java 中。即使哈希映射应该具有 O(1) 查找、更新等,仍然存在一些开销,例如用于检查相等性等。
【解决方案2】:

talentbuddy.co 将这个问题作为他们的编码任务之一。叫下雨,开个账号可以查看其他人的解决方案。

#include <iostream>
#include <vector>

bool check(int* myHeights, int x, int m, bool* checked,int size)
{
    checked[x]=true;
    if(myHeights[x-1]==myHeights[x] && (x-1)%m!=0 && !checked[x-1])
    {
        if(!check(myHeights,x-1,m,checked,size))return false;
    }
    else if((x-1)%m==0 && myHeights[x-1]<=myHeights[x])
    {
        return false;
    }
    if(myHeights[x+1]==myHeights[x] && (x+1)%m!=m-1 && !checked[x+1])
    {
        if(!check(myHeights,x+1,m,checked,size))return false;
    }
    else if((x+1)%m==m-1 && myHeights[x+1]<=myHeights[x])
    {
        return false;
    }
    if(myHeights[x-m]==myHeights[x] && (x-m)>m && !checked[x-m])
    {
        if(!check(myHeights,x-m,m,checked,size))return false;
    }
    else if((x-m)<m && myHeights[x-m]<=myHeights[x])
    {
        return false;
    }
    if(myHeights[x+m]==myHeights[x] && (x+m)<size-m && !checked[x+m])
    {
        if(!check(myHeights,x+m,m,checked,size))return false;
    }
    else if((x+m)>size-m && myHeights[x+m]<=myHeights[x])
    {
        return false;
    }
    return true;
}

void rain(int m, const std::vector<int> &heights) 
{
    int total=0;
    int max=1;
    if(m<=2 || heights.size()/m<=2)
    {
        std::cout << total << std::endl;
        return;
    }
    else
    {
        int myHeights[heights.size()];
        for(int x=0;x<heights.size();++x)
        {
            myHeights[x]=heights[x];
        }
        bool done=false;
        while(!done)
        {
            done=true;
            for(int x=m+1;x<heights.size()-m;++x)
            {
                if(x<=m || x%m==0 || x%m==m-1)
                {
                    continue;
                }

                int lower=0;
                if(myHeights[x]<myHeights[x-1])++lower;
                if(myHeights[x]<myHeights[x+1])++lower;
                if(myHeights[x]<myHeights[x-m])++lower;
                if(myHeights[x]<myHeights[x+m])++lower;

                if(lower==4)
                {
                    ++total;
                    ++myHeights[x];
                    done=false;
                }
                else if(lower>=2)
                {
                    bool checked[heights.size()];
                    for(int y=0;y<heights.size();++y)
                    {
                        checked[y]=false;
                    }
                    if(check(myHeights,x,m,checked,heights.size()))
                    {
                        ++total;
                        ++myHeights[x];
                        done=false;
                    }
                }
            }
        }
    }
    std::cout << total << std::endl;
    return;
}

【讨论】:

  • 注:这不是java,但原理是一样的(真实性我没看代码)
  • 我认为拼出答案并不像他们必须自己翻译逻辑那样有帮助:)
  • 我同意。我只是想确保 OP 没有复制/粘贴,并想知道为什么没有任何效果。
  • 谢谢,很快就会试试这个,让你知道!还有拉塞尔,我不傻哈哈。
  • 所有这些代码都不起作用,它们都适用于简单的测试用例,但不适用于复杂的测试用例。看到人们发送了哪些代码并实际通过了测试用例,这令人不安。看到天才哥们有这么糟糕的测试用例也令人不安。无论如何,我没有进一步,我自己的代码现在仍然是最好的。
猜你喜欢
  • 1970-01-01
  • 2015-01-30
  • 2020-01-21
  • 1970-01-01
  • 2011-01-03
  • 2012-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多