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

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

    You can try this. First decide the size of the grid Lets say its 8 X 8 & assign MIN_X = 0, MIN_Y = 0, MAX_X =7, MAX_Y =7

    Your curren position is represented by thisPosX , thisPosY, then try this:

    int startPosX = (thisPosX - 1 < MIN_X) ? thisPosX : thisPosX-1;
    int startPosY = (thisPosY - 1 < MIN_Y) ? thisPosY : thisPosY-1;
    int endPosX =   (thisPosX + 1 > MAX_X) ? thisPosX : thisPosX+1;
    int endPosY =   (thisPosY + 1 > MAX_Y) ? thisPosY : thisPosY+1;
    
    
    // See how many are alive
    for (int rowNum=startPosX; rowNum<=endPosX; rowNum++) {
        for (int colNum=startPosY; colNum<=endPosY; colNum++) {
            // All the neighbors will be grid[rowNum][colNum]
        }
    }
    

    you can finish it in 2 loops.

提交回复
热议问题