暴力解法!
这代码有点长。但思路很容易理解,根据题意,如何判断多少颗雷,是根据相邻八颗而定的,但是边界和顶点周围并没有八颗。怎么办呢?我想到的是将四个顶点单独处理,边界单独处理,剩下的就是中间的有相邻八颗的。
于是我开始写代码,但在写的过程中,我发现并没法像我想的那样简单分为三种,除了中间点外,边界和顶点每种都有四种情况,于是我便去看其他人的解法,发现他们也是发现没法全部用相邻,于是把数组上下左右各扩大一行,这样就保证所有位置都有八个相邻,后面判断雷也是if和for语句,所以我判定我的思路也可以写出来,但只是较为繁琐,于是可以看到我下面有许多if语句
需要注意的点:1.怎么计数,可以用for循环和中间变量递增就可以优化if过多的问题。
2.字符与数字的转换(可以看到我赋值给数组的时候加了48)
3.其他一些写了才会发现的错误(如中间点一开始忘记设两个中间变量了,直接用一个中间变量做了两次循环)
#include <stdio.h> int main(){ int n,m; scanf("%d %d",&n,&m); getchar(); char a[n][m]; char b[n][m]; for(int i = 0;i<n;i++){ for(int j = 0;j<m;j++){ scanf("%c",&a[i][j]); } getchar(); } for(int i = 0;i<n;i++){ for(int j = 0;j<m;j++){ int count = 0; if(a[i][j] == '*'){ b[i][j] = '*'; } else if(i == 0 && j == 0){ if(a[i][j+1] == '*'){ count++; } if(a[i+1][j] == '*'){ count++; } if(a[i+1][j+1] == '*'){ count++; } else{ } b[i][j] = count+48; } else if(i == 0 && j== m-1){ if(a[i][j-1] == '*'){ count++; } if(a[i+1][j] == '*'){ count++; } if(a[i+1][j-1] == '*'){ count++; } else{ } b[i][j] = count+48; } else if(i == n-1 && j == 0){ if(a[i][j+1] == '*'){ count++; } if(a[i-1][j] == '*'){ count++; } if(a[i-1][j+1] == '*'){ count++; } else{ } b[i][j] = count+48; } else if(i == n-1 && j == m-1){ if(a[i][j-1] == '*'){ count++; } if(a[i-1][j] == '*'){ count++; } if(a[i-1][j-1] == '*'){ count++; } else{ } b[i][j] = count+48; } else if(j == 0){ int temp = i; for(int k = 0;k<3;k++){ if(a[temp-1][j+1] == '*'){ count++; } temp++; } if(a[i-1][j] == '*'){ count++; } if(a[i+1][j] == '*'){ count++; } b[i][j] = count+48; } else if(j == m-1){ int temp = i; for(int k = 0;k<3;k++){ if(a[temp-1][j-1] == '*'){ count++; } temp++; } if(a[i-1][j] == '*'){ count++; } if(a[i+1][j] == '*'){ count++; } b[i][j] = count+48; } else if(i == 0){ int temp = j; for(int k = 0;k<3;k++){ if(a[i+1][temp-1] == '*'){ count++; } temp++; } if(a[i][j-1] == '*'){ count++; } if(a[i][j+1] == '*'){ count++; } b[i][j] = count+48; } else if(i == n-1){ int temp = j; for(int k = 0;k<3;k++){ if(a[i-1][temp-1] == '*'){ count++; } temp++; } if(a[i][j-1] == '*'){ count++; } if(a[i][j+1] == '*'){ count++; } b[i][j] = count+48; } else{ int temp1 = j; int temp2 = j; for(int k1 = 0;k1<3;k1++){ if(a[i-1][temp1-1] == '*'){ count++; } temp1++; } for(int k2 = 0;k2<3;k2++){ if(a[i+1][temp2-1] == '*'){ count++; } temp2++; } if(a[i][j-1] == '*'){ count++; } if(a[i][j+1] == '*'){ count++; } b[i][j] = count+48; } } } for(int i = 0;i<n;i++){ for(int j = 0;j<m;j++){ printf("%c",b[i][j]); } printf("\n"); } return 0; }