采用的算法比较死板,太多if...else语句结合,希望有大牛点评一下下哈!
朋友说可以把雷区矩阵一次性开辟大一点,然后把外围全填零,就可以避免判断端点、边界,只要全部判断八方向就好了。
/** i:行 j:列 四连通[ 上(i-1,j)、 下(i+1,j)、 左(i,j-1)、 右(i,j+1)] 八连通[ 左上(i-1,j-1)、左下(i+1,j-1)、右上(i-1,j+1)、右下(i+1,j+1) ] **/ #include <stdio.h> #define M 4 #define N 4 void output(char op[M][N]) { for(int i=0;i<M;i++) { for(int j=0;j<N;j++) { if(op[i][j] == '*') printf("%c ",op[i][j]); else printf("%d ",op[i][j]-'0'); } printf("\n"); } } void saolei(char b[M][N]) { int i,j; for(i=0;i<M;i++) { for(j=0;j<N;j++) { if(b[i][j] != '*') { b[i][j]='0'; if(i==0 && j==0)//左上顶点 { if(b[i+1][j]=='*') b[i][j]++; if(b[i][j+1]=='*') b[i][j]++; if(b[i+1][j+1]=='*') b[i][j]++; continue; } else if(i==M-1 && j==0)//左下顶点 { if(b[i-1][j] == '*') b[i][j]++; if(b[i][j+1] == '*') b[i][j]++; if(b[i-1][j+1] == '*') b[i][j]++; continue; } else if(i==0 && j==N-1)//右上顶点 { if(b[i][j-1] == '*') b[i][j]++; if(b[i+1][j] == '*') b[i][j]++; if(b[i+1][j-1] == '*') b[i][j]++; continue; } else if(i==M-1 && j==N-1)//右下顶点 { if(b[i][j-1] == '*') b[i][j]++; if(b[i-1][j] == '*') b[i][j]++; if(b[i-1][j-1] == '*') b[i][j]++; continue; } else if(j==0)//左边界 { if(b[i-1][j] == '*') b[i][j]++; if(b[i+1][j] == '*') b[i][j]++; if(b[i][j+1] == '*') b[i][j]++; if(b[i-1][j+1] == '*') b[i][j]++; if(b[i+1][j+1] == '*') b[i][j]++; continue; } else if(j==N-1)//右边界 { if(b[i-1][j] == '*') b[i][j]++; if(b[i+1][j] == '*') b[i][j]++; if(b[i][j-1] == '*') b[i][j]++; if(b[i-1][j-1] == '*') b[i][j]++; if(b[i+1][j-1] == '*') b[i][j]++; continue; } else if(i==0)//上边界 { if(b[i][j-1] == '*') b[i][j]++; if(b[i][j+1] == '*') b[i][j]++; if(b[i+1][j] == '*') b[i][j]++; if(b[i+1][j+1] == '*') b[i][j]++; if(b[i+1][j-1] == '*') b[i][j]++; continue; } else if(i==M-1)//下边界 { if(b[i][j-1] == '*') b[i][j]++; if(b[i][j+1] == '*') b[i][j]++; if(b[i-1][j] == '*') b[i][j]++; if(b[i-1][j+1] == '*') b[i][j]++; if(b[i-1][j-1] == '*') b[i][j]++; continue; } else { if(b[i-1][j] == '*') b[i][j]++; if(b[i+1][j] == '*') b[i][j]++; if(b[i][j-1] == '*') b[i][j]++; if(b[i][j+1] == '*') b[i][j]++; if(b[i+1][j+1] == '*') b[i][j]++; if(b[i-1][j-1] == '*') b[i][j]++; if(b[i+1][j-1] == '*') b[i][j]++; if(b[i-1][j+1] == '*') b[i][j]++; continue; } } } } } void main() { char a[M][N]={{'*','.','.','.'}, {'.','.','.','.'}, {'.','*','.','.'}, {'.','.','.','.'}}; printf("初始为4*4的雷区矩阵(*代表地雷,.代表无地雷):\n"); for(int i=0;i<M;i++) { for(int j=0;j<N;j++) { printf("%c ",a[i][j]); } printf("\n"); } saolei(a); printf("经计算机扫描后的结果:\n"); output(a); }