简体   繁体   English

在Java中搜索2D数组行

[英]Searching an 2D array row in java

I am searching an 2D array that has 1 and 0 . 我正在搜索具有102D数组 If there is an adjacent 3 to a 0, the 0 gets converted to a 3. I have figured out how to search a row once, but I would like the same for loop to repeat until all the 0's have been converted to 3. Thanks in advance for the help. 如果0旁边有一个3,则0会转换为3。我想出了如何搜索一次行,但是我想重复同样的for循环,直到所有0都转换为3。提前寻求帮助。

Here is a visual depiction. 这是一个视觉描绘。 So if I am searching the 2nd row, I will find the first 0 touching a 3, but then I want to go through the same row and find the next 0 that is touching a 3. I hope that clarifies! 因此,如果我搜索第二行,我会发现第一个0碰到3,但是接下来我想遍历同一行并找到下一个碰到3的0。希望您能澄清一下! :) :)

1 1 1 1 1 3 1 1 1 1 1 1 1 3 1 1

1 0 1 1 0 0 1 1 1 0 1 1 0 0 1 1

1 1 1 1 0 1 1 1 1 1 1 1 0 1 1 1

etc. 等等

I start the search on row with index 1 and I find the first 0 that touches a 3 and convert it to a 3. So I have the following, I then need to go back and repeat the process until the remainding 0 is converted to a 3 and then repeat for each row: 我从索引为1的行开始搜索,找到第一个与3接触的0,然后将其转换为3。因此,我有以下内容,然后我需要返回并重复该过程,直到将剩余的0转换为a。 3,然后对每行重复一次:

1 1 1 1 1 3 1 1 1 1 1 1 1 3 1 1

1 0 1 1 0 3 1 1 1 0 1 1 0 3 1 1

1 1 1 1 0 1 1 1 1 1 1 1 0 1 1 1

    public boolean searchRows(){
    boolean found = false;
    for (int c = 0; c < cave[rowIndex].length; c++){

        if(cave[rowIndex][c]==0){
            if (cave[rowIndex-1][c] == 3){
                cave[rowIndex][c] = 3;
                found=true;
            }
            else if(cave[rowIndex][c-1] == 3){
                    cave[rowIndex][c] = 3;}
            else {found=false;}
        }
    }   
    return found;
}

It seems like your for loop is working fine to go through the one row. 似乎您的for循环可以正常工作以遍历一行。 It looks like you aren't checking all of the possible elements that could be touching the one you are currently looking at. 看来您并未检查所有可能触及您当前正在查看的元素。 It looks like you are checking the element directly above it and the one directly to the left of it. 看起来您正在检查位于其正上方的元素,并且正位于其左侧的元素。 You should be checking whatever other directions your problem asks for as well. 您还应该检查问题所要求的其他方向。 You should also be checking that you aren't going to be checking an array index that doesn't exist so that you don't get an ArrayIndexOutOfBounds error. 您还应该检查一下,不要检查不存在的数组索引,这样就不会出现ArrayIndexOutOfBounds错误。 Along with that make sure you are are setting your found boolean anytime that you actually find a zero that will be turned into a 3. Currently you are only setting the found to true in one case and not the other. 除此之外,请确保您在实际找到要变成3的零的任何时候设置发现的布尔值。当前,您仅在一种情况下将Found设置为true,而在另一种情况下则不设置为true。

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

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