Minesweeper Numbers
Completed
Read a grid of * (mines) and .. Print it with every . replaced by the number of mines in its 8 neighbouring cells.
Input
r c, then r rows (max 10×10).
Output
r rows.
Example
Input
3 4 *... ..*. ....
Output
*211 12*1 0111
Editor
C
Hints
Check all 8 neighbours, staying inside the grid.
Solution explanation
Each row is read as a string with %s into a row of a 2D char array.
Show solution
#include <stdio.h>
int main() {
int r, c;
char g[10][12];
scanf("%d %d", &r, &c);
for (int i = 0; i < r; i++) scanf("%s", g[i]);
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (g[i][j] == '*') {
printf("*");
continue;
}
int count = 0;
for (int di = -1; di <= 1; di++) {
for (int dj = -1; dj <= 1; dj++) {
int ni = i + di, nj = j + dj;
if (ni >= 0 && ni < r && nj >= 0 && nj < c && g[ni][nj] == '*') count++;
}
}
printf("%d", count);
}
printf("\n");
}
return 0;
}