简体   繁体   中英

Find adjacent element in 2D array

I've been trying to get over a problem:

Let's say, you have an 3*4 (3 row 4 col):

相同游戏示例

Let's take A[1][3] for example: He's adjacent to the A[2][3] , who is adjacent to A[2][2]

My goal, like the "SameGame" Game, is to find a way in order to have every adjacent similar characters' positions in an array in order to highlight them.

At first, I was thinking about doing a loop to check neighbors everytime I found some adjacent similar character, but it seems like a lot of pain for something like this.

    if((this.tabi[x][y] == this.tabi[x+1][y])) {
        this.group[x+1][y] = this.tabi[x+1][y];
        this.group_size++;
        // call it again for this.tabi[x+1][y]
    }
}

Is there a more "performant-wise" solution?

The board is generated randomly:

for (i=0; i<row; i++) {
    for (j=0; j<col; j++) {
        tab[i][j] = A OR B OR C
    }
}

Thanks !

You could use a pathfinding algorithm like Dijkstra or Fjord-Warshall between two Group-Elements and treat every other group as an obstacle.

It's hard to tell, if you don't post a bit more about how you manage your playing field, elements and groups.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM