Reputation: 95
I am trying to count the number of 1s in the neighboring cells in this 2D array. My approach is to check for every cell that is within the range and exclude the impractical ones through the conditional statement.
public static int countMines(int [][] mines, int myR, int myC)
{
int r;
int c;
int count = 0;
for(r = myR - 1; r <= myR + 1; r++)
for(c = myC - 1; c <= myC + 1; c++)
if( r >= 0 && r < mines.length && c >= 0 && c < mines.length
&& r != myR && c != myC && mines[r][c] == 1)
count++;
return count;
}
This is the code I have so far. It accepts the 2D array and the coordinate of the cell you want to search its neighbors. But it DOES NOT work as I intend it. For example,
When countMines(m, 0,0)
is called with m
being as follows
[1] [0] [1] [1]
[1] [0] [1] [1]
[0] [0] [1] [0]
[1] [1] [0] [0]
the method return 0
, as oppose to 1
.
Please tell me if this isn't clear enough. Thank you for your help in advance!
Upvotes: 0
Views: 287
Reputation: 1620
Without using any loops, you could use:
int count = 0;
// Check left of cell
if(myC > 0 && myC < mines.length)
count += mines[myR][myC - 1]
// Check right of cell
if(myC >= 0 && myC < mines.length -1)
count += mines[myR][myC + 1]
// Check top of cell
if(myR > 0 && myR < mines.length)
count += mines[myR - 1][myC]
// Check bottom of cell
if(myR >= 0 && myR < mines.length -1)
count += mines[myR + 1][myC]
Upvotes: 1
Reputation: 3019
The problem is with your clause ... && r != myR && c != myC && ...
.
You intend to avoid the (myR, myC)
cell, but this will avoid all cells in the row myR
and all cells in the column myC
.
This should instead be changed to:
... && !(r == myR && c == myC) && ...
Or through De'Morgan's laws:
... && (r != myR || c != myC) && ...
That way, it will check so long as both values are not equal to the skipped values, opposed to if either value is.
An alternative would be utilizing a delta-values array such as:
private static final int[][] DELTA = new int[][]{
{-1, -1},
{0, -1},
{1, -1},
{1, 0},
{1, 1},
{0, 1},
{-1, 1},
{-1, 0}
};
Then using a single loop to access each offset.
Upvotes: 3