在2d数组中搜索对角线

时间:2014-12-11 21:06:21

标签: java arrays

我正试图在2D数组中对角搜索连接四游戏。我以为我弄清楚了,但显然我错了。第一组for循环工作正常,从右到左,对角线搜索。第二组for循环不起作用。我认为我所要做的就是将一些积极的迹象切换为否定,并且它起作用。最终,通过更改GRID_HEIGHT-1,我能够让它部分工作......但是我一直遇到绑定错误。在这一点上任何帮助将不胜感激。此外,2d阵列的网格为5x4。所以它真的连接3.

    for (int y = 0; y <= GRID_HEIGHT-3; y++) {
        for (int x = 0; x <= GRID_WIDTH-3; x++) {
            if (    
                    state[y][x] != Player.NONE && 
                    state[y][x] == state[y+1][x+1] &&
                    state[y+1][x+1] == state[y+2][x+2]
                    ) return state[y][x];
        }
    }
    for (int y = 0; y <= GRID_HEIGHT-3; y++) {
        for (int x = 0; x <= GRID_WIDTH-3; x++) {
            if (    
                    state[y][x] != Player.NONE && 
                    state[y][x] == state[y-1][x-1] &&
                    state[y-1][x-1] == state[y-1][x-2]
                    ) return state[y][x];
        }
    }


    return Player.NONE;

}

2 个答案:

答案 0 :(得分:2)

对于第二组循环,您将从索引中减去,这意味着索引可以低于零。你需要循环从零开始。

for (int y = 2; y < GRID_HEIGHT; y++) {
    for (int x = 2; x < GRID_WIDTH; x++) {
        if (    
                state[y][x] != Player.NONE && 
                state[y][x] == state[y-1][x-1] &&
                state[y-1][x-1] == state[y-2][x-2]
                ) return state[y][x];
    }
}

此外,通常你应该说(x

答案 1 :(得分:0)

而不是从0迭代到GRID_HEIGHT-3,而是从GRID_HEIGHT向下迭代到3。