Finding valid neighbors in 2D array

前端 未结 7 567
情书的邮戳
情书的邮戳 2021-01-22 07:13

So, I have a 4x4 2D array (it will always be these dimensions). Starting with a location on the array, some row and column, I want to find all of its valid neighbors. So far, I

7条回答
  •  时光取名叫无心
    2021-01-22 07:47

    Unfortunately by writing code you are telling a computer what to do and the computer doesn't know anything more than what you tell it.

    You can automate this kind of thing a little with nonstandard loop logic though I guess:

    for (int coff = -1; coff < 3; coff += 2) {
        for (int roff = -1; roff < 3; roff += 2) {
    
            if (    col + coff >= 0 &&
                    col + coff < array.length &&
                    row + roff >= 0 &&
                    row + roff < array[row].length) {
    
                // do stuff with array[col + coff][row + roff]
    
            }
        }
    }
    

    That loop structure will flip the column and row offset from -1 to 1 and then break when they become 3 on the 3rd iteration.

    But note that in your code, checking against !(stuff) > 4 will give you an ArrayIndexOutOfBounds exception because remember the last index is 4 - 1.

提交回复
热议问题