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

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

    How about this:

    private static void printNeighbours(int row, int col, int[][] Data, int rowLen, int colLen)
    {
        for(int nextR=row-1; nextR<=row+1; nextR++)
        {
            if(nextR<0 || nextR>=rowLen)
                continue;  //row out of bound
            for(int nextC=col-1; nextC<=col+1; nextC++)
            {
                if(nextC<0 || nextC>=colLen)
                    continue;  //col out of bound
                if(nextR==row && nextC==col)
                    continue;    //current cell
                System.out.println(Data[nextR][nextC]);
            }
        }
    }
    

提交回复
热议问题