I have a task of implementing recursion in a simulated minesweeper game in
C. It should basically call itself to clear neighboring cells, provided it is possible to do so. I would appreciate any help in pointing out the error in my algorithm. And please bear in mind that I have only learnt programming for 6 weeks so I may not understand advanced explanations. Thank you!
(PS: I would like to post the actual question but it seems like it is not possible to do so here)
What I have tried:
#include <stdio.h>
#include <stdbool.h>
#define ROW 16 //max number of rows
#define COL 30 //max number of columns
void readBoard(int board[][COL], int m, int n);
void printBoard(int board[][COL], int m, int n);
int countNeighbour(int board[][COL], int r, int c, int m, int n);
bool isValid(int r, int c, int m, int n);
bool allCleared(int board[][COL], int m, int n);
void clearNeighbours(int board[][COL], int r, int c, int m, int n);
int main(void) {
int r, c, m, n, board[ROW][COL]={{0}};
scanf("%d%d", &m, &n);
readBoard(board, m, n); do {
scanf("%d%d", &r, &c);
if(board[r][c] < 9 && isValid(r,c,m,n) == true) { if(countNeighbour(board, r, c, m, n) == 0) {
clearNeighbours(board, r, c, m, n);
}
} else break; } while (allCleared(board,m,n) == false);
printBoard(board, m, n);
return 0;
}
bool allCleared(int board[][COL], int m, int n) {
int i,j;
for(i=0; i<m; i++) {
for(j=0; j<n; j++) {
if(board[i][j] == -1) {
return false;
}
}
}
return true;
}
bool isValid(int r, int c, int m, int n) {
if(r>=0 && r<=m && c>=0 && c<=n) {
return true;
}
return false;
}
void readBoard(int board[][COL], int m, int n) {
int i,j;
for(i=0; i<m; i++) {
for(j=0; j<n; j++) {
scanf("%d", &board[i][j]);
}
}
}
void printBoard(int board[][COL], int m, int n) {
int i, j;
for(i=0; i<m; i++) {
for(j=0; j<n; j++) {
if(board[i][j] == -1) {
printf(".");
}
else if( board[i][j] >= 9) {
printf("*");
} else {
printf("%d", board[i][j]);
}
}
printf("\n");
}
}
int countNeighbour(int board[][COL], int r, int c, int m, int n) {
if(board[r][c]!=-1) return board[r][c];
if(isValid(r-1,c,m,n) && board[r-1][c] == 9) {
board[r][c]++;
}
if(isValid(r-1,c-1,m,n) && board[r-1][c-1] == 9) {
board[r][c]++;
}
if(isValid(r,c-1,m,n) && board[r][c-1] == 9) {
board[r][c]++;
}
if(isValid(r+1,c+1,m,n) && board[r+1][c+1] == 9) {
board[r][c]++;
}
if(isValid(r,c+1,m,n) && board[r][c+1] == 9) {
board[r][c]++;
}
if(isValid(r+1,c,m,n) && board[r+1][c] == 9) {
board[r][c]++;
}
if(isValid(r+1,c-1,m,n) && board[r+1][c-1] == 9) {
board[r][c]++;
}
if(isValid(r-1,c+1,m,n) && board[r-1][c+1] == 9) {
board[r][c]++;
}
board[r][c]++; return board[r][c];
}
void clearNeighbours(int board[][COL], int r, int c, int m, int n) {
int row[] = {1,0,-1,0,1,1,-1,-1}; int col[] = {0,1,0,-1,1,-1,1,-1}; int i;
countNeighbour(board,r,c,m,n);
if(board[r][c] != 8) return;
for(i = 0;i<8;i++) { int nextRow = r + row[i], nextCol = c + col[i];
if(isValid(nextRow,nextCol,m,n) && board[r][c] == -1) {
clearNeighbours(board,nextRow,nextCol,m,n); }
}
}