You should also outline your algorithm along with the code to give out a better idea of how you are approaching the problem. It's really difficult to understand this code without an accompanying algorithm.
You could outline your algorithm in plain english, doesn't have to be pseudocode. It will help you understand the problem and solution better. For instance, something like this:
- look at each mine
- increment all it's non-mine neighbors
I think you are over-complicating the way you check for boundary conditions. Let's assume if the minefield was infinitely large in each direction. If we then picked any random cell(i,j)
, it's 8 neighbours would be at:
cell(i-1, j-1) // top-left
cell(i-1, j) // top
cell(i-1, j+1) // top-right
cell(i, j-1) // left
cell(i, j+1) // right
cell(i+1, j-1) // bottom-left
cell(i+1, j) // bottom
cell(i+1, j+1) // bottom-right
Back to the actual finite-length case now. I'd suggest that instead of pre-calculating whether a cell is within bounds, you should always check all 8 neighbors, and discard the invalid ones.
A function that checks if a cell is valid is easy to write:
bool is_cell_valid(int x, int y, int rows, int cols) {
if(x < 0 || x >= cols) {
return false;
}
if(y < 0 || y >= rows) {
return false;
}
return true;
}
I understand you algorithm now finally :)
- look at each non-mine cell
- change its value to the number of neighboring mines
The double checking is happening because you are not checking for all variables that are changing. For example, in this condition you are using iLEFT and jLEFT to go to the top-left cell. Since both variables are being used, you have to make sure that both of them are non-zero.
if(box[i-iLEFT][j-jLEFT]==-1)
{
if(i-iLEFT!=i) // trying to avoid double checking
count+=1;
}
The above should instead be
if(iLEFT != 0 && jLEFT != 0)
{
if(box[i-iLEFT][j-jLEFT]==-1)
count+=1;
}
And this check should be applied on each of the 8 cells, not just the diagonal cells.
Here's a tiny alternative to go through all 8 cells that are adjacent to some cell at (x, y) without using an if for each neighbor.
for(int i = -1; i < = 1; i++) {
for(int j = -1; j <= 1; j++) {
if(i == 0 && j == 0) {
continue;
}
if(is_cell_valid(x + i, y + j, N, N);
// cell is adjacent and within boundaries
// do whatever calculations are needed
}
}
}