Domanda

I've created a 12x12 grid, and within this grid I have created 'infected' tiles, when one infected tile is surrounded by other infected tiles, the surrounded cell becomes a diseased tile. I was wondering if there was a nice way of checking adjacent, in bounds cells for their value?

public static void diseaseTiles() {
    int i, j;
    for(i = 0; i < 12; i++) {
        for(j = 0; j < 12; j++) {
            if(myGrid[i][j] == 'I'){
                int left, right, up, down;
                if(i == 0) {
                    left = 1;
                }
                if(i == 11) {
                    right = 1;
                }
                if(j == 0) {
                    up = 1;
                }
                if(j == 11) {
                    down = 1;
                }
                //this is where I've gotten stuck
                //I was going to use the above int's to determine
                //whether or not the adjacent tile in that direction
                //should be checked (they're the border of the grid)
            }
        }
    }
}
È stato utile?

Soluzione

You can check if a cell is infected by taking advantage of short-circuited evaluation:

boolean leftInfected = (i!=0) && myGrid[i-1][j]=='I';
boolean rightInfected = (i!=11) && myGrid[i+1][j]=='I';
boolean topInfected = (j!=0) && myGrid[i][j-1]=='I';
boolean bottomInfected = (j!=11) && myGrid[i][j+1]=='I';

After that, you could check if all four are infected:

if (leftInfected && rightInfected && topInfected && bottomInfected) {
    myGrid[i][j] = 'D';
}

Altri suggerimenti

You might consider padding your array with a boundary one cell deep around each edge, so your 12x12 would become a 14x14. Make each cell in the boundary infected. You can then loop over the interior cells (ie rows 1:12, cols 1:12) without having to check that the cell is at the edge all the time.

I believe a better option is to define a helper array that defines the valid neighbors and iterate using it. Advantage of my approach is that it makes it very easy to change which are the valid neighbors(say you want to have 8 neighbors allowing to go by diagonal instead of only 4):

int moves[][] = {{-1,0}, {0, -1}, {1, 0},  {0, 1} };
for (int i = 0; i < 12; i++) {
    for (int j = 0; j < 12; j++) {
      for (int l = 0; l < 4 /* moves.length */; ++l) {
        int ti = i + move[l][0];
        int tj = j + move[l][1];
        if (ti <= 0 || ti >= 12 || tj < 0 || tj >= 12) {
          continue;
        }
        // cell (ti, tj) is valid neighbor do something with it.
      }
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top