More efficient way to check neighbours in a two-dimensional array in Java

前端 未结 7 1779
难免孤独
难免孤独 2020-12-14 11:50

Hey all, for a few of my college assignments I\'ve found the need to check neighbouring cells in 2-dimensional arrays (grids). The solution I\'ve used is a bit of a hack usi

相关标签:
7条回答
  • 2020-12-14 12:56

    The basic principle is not to access things that are out of bounds -- so either protect the bounds or don't go out of bounds in the first place. That is, start at a place where you won't immediately go out of bounds and stop before you get out of bounds.

    for ( int row = 1; row < grid.length - 1; row++ ) {
        for ( int col = 1; col < grid.length - 1; col++ ) {
            // this section will usually be in a function
            // checks neighbours of the current "cell"
            for ( int rowMod = -1; rowMod <= 1; rowMod++ ) {
                for ( int colMod = -1; colMod <= 1; colMod++ ) {
                    if ( someVar == grid[row+rowMod][col+colMod] ) {
                        // do something
                    }
                }
            }
            // end checking neighbours
        }
    }
    

    Like your current code, this doesn't necessarily deal appropriately with edge conditions -- that is, it applies a 3x3 grid everywhere that the 3x3 grid fits within the matrix, but does not shrink the grid to a 2x2, 2x3 or 3x2 grid when on the edge of the matrix. It will, however, allow a method in the main body checking a 3x3 grid to observe every cell in the matrix.

    0 讨论(0)
提交回复
热议问题