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

前端 未结 7 1797
难免孤独
难免孤独 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:32

    why can't you check row+rowMod and col+colMod for validity before array access?

    something like:

     r=row+rowMod;
     c=col+colMod;
     if (r < 0 || c < 0 || r >= grid.length || c >= grid.length) continue;
    

    alternatively (no continue):

     if (r >= 0 && c >= 0 && r < grid.length && c < grid.length && 
         someVar == grid[r][c]) { /* do something */ }
    

提交回复
热议问题