题解 | #扫雷#
扫雷
https://www.nowcoder.com/practice/d5f277427d9a4cd3ae60ea6c276dddfd
#include<stdio.h>
int get_count(char arr[1001][1001], int i, int j)
{
if (arr[i][j] == '*')//arr[i][j]是雷就返回-1,不是雷就计算周围有多少个雷。
return -1;
int count = 0;
int x = i - 1;
while (x <= i + 1)//排查9个位置,arr[i][j]位置肯定不是雷。
{
int y = j - 1;
while (y <= j + 1)
{
if (arr[x][y] == '*')
count++;
y++;
}
x++;
}
return count;
}
int main()
{
char arr[1001][1001] = { 0 };
int n = 0;
int m = 0;
scanf("%d %d", &n, &m);
//布置雷
for (int i = 1; i <= n; i++)
{
getchar();
for (int j = 1; j <= m; j++)
{
scanf("%c", &arr[i][j]);
}
}
//排查雷
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
int ret = get_count(arr, i, j);//返回周围雷的个数,如果该位置就是雷则返回-1.
if (ret == -1)
{
arr[i][j] = '*';
}
else
{
arr[i][j] = '0' + ret;//将数字转化为字符
}
}
}
//打印排雷结果
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
printf("%c", arr[i][j]);
}
printf("\n");
}
return 0;
}


