简体   繁体   English

在二维数组中查找连续的 0

[英]Find consecutive 0s in a two dimensional array

I am working on a homework assignment where I need to find all the 0s connecting to the one on the top, change them to 2s, and return the amount changed.我正在做一项家庭作业,我需要找到连接到顶部的所有 0,将它们更改为 2,然后返回更改的金额。

So far I have:到目前为止,我有:

    int[][] cavern = {{1,1,1,1,1,0,1},
                      {1,0,0,1,1,0,1},
                      {1,1,1,0,0,0,1},
                      {1,1,0,0,1,1,1},
                      {1,0,1,0,1,0,1},
                      {1,0,1,0,0,0,1},
                      {0,0,0,1,1,1,0},
                      {1,1,1,0,0,0,1}};

    //reads the size of the array
    ...code

    //prints array as a grid (original)
    ...code

    //find zero value in first row
    ...code, sets value to 2


    //change connecting zeros to 2's
    for(int r=0; r<cavern.length; r++)
    for(int c = 0; c < cavern[0].length; c++){
        if(cavern[r][c] == 2){
            if((c+1) < cavern[r].length && cavern[r][c+1] == 0){cavern[r][c+1] = 2;}
            else if((c-1) < cavern[r].length && cavern[r][c-1] == 0){cavern[r][c-1] = 2;}
            else if((r+1) < cavern.length && cavern[r+1][c] == 0){cavern[r+1][c] = 2;}
            else if((r-1) < cavern.length && cavern[r-1][c] == 0){cavern[r-1][c] = 2;}
            }   
    }   

    //Print the size of the array
            ...code

    //prints array as a grid with colored values
            ...code

with result:结果:

1 1 1 1 1 2 1 
1 0 0 1 1 2 1 
1 1 1 0 2 2 1 
1 1 0 0 1 1 1 
1 0 1 0 1 0 1 
1 0 1 0 0 0 1 
0 0 0 1 1 1 0 
1 1 1 0 0 0 1

As you can see, the 2s stop after just a few and does not continue to loop through to the end of the zeros.如您所见,2s 仅在几个之后停止,并且不会继续循环到零的末尾。 I feel like I am missing something simple, or made a silly mistake.我觉得我错过了一些简单的东西,或者犯了一个愚蠢的错误。 I haven't done any programming in years and some basic things are slipping my mind.我已经好几年没做过任何编程了,一些基本的事情让我一头雾水。

I am also having trouble counting all 2's that show up in the array, no matter what I try I either get a value of 1, 2 or it returns an error.我也无法计算数组中出现的所有 2,无论我尝试什么,我要么得到 1、2 的值,要么返回错误。

Any help would be appreciated.任何帮助,将不胜感激。

EDIT: With the first answer's suggestions I am now getting this:编辑:有了第一个答案的建议,我现在得到了这个:

 1 1 1 1 1 2 1  
 1 0 0 1 1 2 1  
 1 1 1 2 0 2 1   
 1 1 0 2 1 1 1   
 1 2 1 2 1 2 1   
 1 2 1 2 0 2 1   
 0 0 0 1 1 1 0   
 1 1 1 2 2 2 1 
int numberOfTwos = 0;
for(int r = 0; r < cavern.length; r++){
    for(int c = 0; c < cavern[r].length; c++){
        if(cavern[r][c] == 0){
           // We check that we're not on the last row, and also if the next             
           // row is also equals to 0
           if(r < cavern.length-1 && cavern[r+1][c]==0){
              numberOfTwos++;
              // We change both 0's to 2's
              cavern[r][c]=2
              cavern[r+1][c]=2;
           }
           // We also change if we're on a 2 and not on the last column
           else if(c < cavern[0].length-1 && cavern[r][c]==2){
              // if the next one is a 0, we change it for a 2
              if(cavern[r][c+1] ==0){
                 //numberOfTwos++;
                 cavern[r][c+1] =2;
              }
              // if the one under is also a 0, we change it for a 2
              else if(r < cavern.length-1 && cavern[r+1][c] ==0){
                 numberOfTwos++;
                 cavern[r+1][c] =2;
              }
           }
           // We only gonna change the current cavern[r][c] if there's no                                  
           //more rows to check
           else if(r == cavern.length-1){
              numberOfTwos++;
              cavern[r][c]=2;
           }
        }
    } 
}

I think this should work.我认为这应该有效。 It'll check if the value of every cavern[r][c] is equals to zero, then it'll check if the row under is also a zero ( only if there is a row under that's why r < column.length-1 ) , and if yes, it'll change their values to 2's.它会检查每个cavern[r][c]的值是否等于0,然后它会检查下面的行是否也为零(只有当下面有一行时,这就是r < column.length-1 ) ,如果是,它会将它们的值更改为 2。 Else it'll only change the values of the cavern[r][c] since there would be no rows under.否则它只会改变cavern[r][c]的值,因为下面没有行。

Edit : You can't connect the 0 from top to bottom, it stops 2 line before the last one.编辑:您不能将 0 从上到下连接,它会在最后一行之前停止 2 行。 I don't know if it's a typo or not.不知道是不是笔误。

This seems to me to be something that a recursive solution would be more elegant for.在我看来,递归解决方案会更优雅。

Have a function called changeZeroToTwoPlusPartners() which simply does the job for a single cell, plus all valid partner cells.有一个名为changeZeroToTwoPlusPartners()的函数,它只为单个单元格以及所有有效的伙伴单元格完成这项工作。 In pseudo-code, that would be along the lines of:在伪代码中,这将是:

def changeZeroToTwoPlusPartners(array, xwidth, yheight, xpos, ypos):
    # No action if we have moved outside the array.

    if xpos < 0 or xpos >= xwidth or ypos < 0 or ypos >= yheight:
        return

    # No action if cell is not a zero.

    if array[xpos,ypos] != 0:
        return

    # Change it then do all partners of that cell (right, left, down, up).

    array[xpos,ypos] = 2

    changeZeroToTwoPlusPartners(array, xwidth, yheight, xpos+1, ypos)
    changeZeroToTwoPlusPartners(array, xwidth, yheight, xpos-1, ypos)
    changeZeroToTwoPlusPartners(array, xwidth, yheight, xpos, ypos+1)
    changeZeroToTwoPlusPartners(array, xwidth, yheight, xpos, ypos-1)

The checks up front prevent you from moving outside of the array and processing any non-zero cells.预先检查可防止您移出数组并处理任何非零单元格。

The immediate setting of the cell to two, in conjunction with that check above that filters out non-zero cells, will prevent infinite regress since moving back to a cell that you've already processed will be filtered as not being zero any more (it will now be a two).将单元格立即设置为 2,结合上面过滤掉非零单元格的检查,将防止无限回归,因为移回您已经处理过的单元格将被过滤为不再为零(它现在将是两个)。

Then, to use this function, you just need to call it for each cell in the first row:然后,要使用此函数,您只需为第一行中的每个单元格调用它:

for xpos in 0 to xwidth-1 inclusive:
    changeZeroToTwoPlusPartners(array, xwidth, yheight, xpos, 0)

In terms of a proof-of-concept, here's some Python code that does what you need:就概念验证而言,这里有一些 Python 代码可以满足您的需求:

def changeZeroToTwoPlusPartners(array, xwidth, yheight, xpos, ypos):
    if xpos < 0 or xpos >= xwidth or ypos < 0 or ypos >= yheight:
        return
    if array[ypos][xpos] != 0:
        return

    array[ypos][xpos] = 2

    changeZeroToTwoPlusPartners(array, xwidth, yheight, xpos+1, ypos)
    changeZeroToTwoPlusPartners(array, xwidth, yheight, xpos-1, ypos)
    changeZeroToTwoPlusPartners(array, xwidth, yheight, xpos, ypos+1)
    changeZeroToTwoPlusPartners(array, xwidth, yheight, xpos, ypos-1)

cavern = [[1,1,1,1,1,0,1],
          [1,0,0,1,1,0,1],
          [1,1,1,0,0,0,1],
          [1,1,0,0,1,1,1],
          [1,0,1,0,1,0,1],
          [1,0,1,0,0,0,1],
          [0,0,0,1,1,1,0],
          [1,1,1,0,0,0,1]]

for line in cavern:
    print(line)

for xpos in range(len(cavern[0])):
    changeZeroToTwoPlusPartners(cavern, len(cavern[0]), len(cavern), xpos, 0)

print("-----")
for line in cavern:
    print(line)

The output is (and you'll see the transformation is correct if you do it manually, changing every 0 on the top line to a 2 then recursively changing any 0 adjacent to a 2 into yet another 2 ):输出是(如果您手动进行转换,您将看到转换是正确的,将顶行上的每个0更改为2然后递归地将与2相邻的任何0更改为另一个2 ):

[1, 1, 1, 1, 1, 0, 1]
[1, 0, 0, 1, 1, 0, 1]
[1, 1, 1, 0, 0, 0, 1]
[1, 1, 0, 0, 1, 1, 1]
[1, 0, 1, 0, 1, 0, 1]
[1, 0, 1, 0, 0, 0, 1]
[0, 0, 0, 1, 1, 1, 0]
[1, 1, 1, 0, 0, 0, 1]
-----
[1, 1, 1, 1, 1, 2, 1]
[1, 0, 0, 1, 1, 2, 1]
[1, 1, 1, 2, 2, 2, 1]
[1, 1, 2, 2, 1, 1, 1]
[1, 0, 1, 2, 1, 2, 1]
[1, 0, 1, 2, 2, 2, 1]
[0, 0, 0, 1, 1, 1, 0]
[1, 1, 1, 0, 0, 0, 1]
def BitmapHoles(strArr):
    ans = 0
    n = len(strArr)
    for i in range(n):
        for j in range(len(strArr[i])):
            if strArr[i][j] == 0:
                if i < n-1 and strArr[i+1][j] == 0:
                    ans +=1
                    strArr[i][j] = 2
                    strArr[i+1][j] = 2
                elif j < len(strArr[0])-1 and strArr[i][j] == 2:
                    if strArr[i][j+1] == 0:
                        strArr[i][j+1] = 2
                    elif i < n-1 and strArr[i+1][j] == 0:
                        ans += 1
                        strArr[i+1][j] = 2
                elif i == n-1:
                    ans += 1
                    strArr[i][j] = 2

    return ans


print(BitmapHoles([[0,1,1,1,1],[0,1,1,0,1],[0,0,0,1,1],[1,1,1,1,0]]))

print(BitmapHoles([[1,1,1,1,1,0,1],
                      [1,0,0,1,1,0,1],
                      [1,1,1,0,0,0,1],
                      [1,1,0,0,1,1,1],
                      [1,0,1,0,1,0,1],
                      [1,0,1,0,0,0,1],
                      [0,0,0,1,1,1,0],
                      [1,1,1,0,0,0,1]]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM