好奇,想用二维数组实现扫雷的埋雷和统计周围雷的数目,刚开始用一个二维数组(相对小的那个,后文称:小数组)保存数据,发现统计的时候边缘情况有点麻烦,就又定义了一个比原来列行都大2的二维数组(后文称:大数组)。把原来的保存的数据放到大数组中间,然后统计大数组,统计结果放回小数组。
代码:
#include<stdio.h> #include<time.h> #define ROW 16 #define COL 30 #define TROW 18 #define TCOL 32 #define MINE_NUM 99 #define MINE_FLAG 9 void initMine(int rec[][COL],int m,int n); void initTmp(int rec[][TCOL],int m,int n); void showMine(int rec[][COL],int m,int n); void showTmp(int rec[][TCOL],int m,int n); void setMine(int rec[][COL],int recTmp[][TCOL],int m,int n); void sniffeMine(int rec[][COL],int recTmp[][TCOL],int m,int n); int isMine(int rec[][TCOL],int m,int n); int main(){ int mineRec[ROW][COL]; int tmpRec[TROW][TCOL]; initMine(mineRec,ROW,COL); initTmp(tmpRec,TROW,TCOL); setMine(mineRec,tmpRec,ROW,COL); sniffeMine(mineRec,tmpRec,ROW,COL); showMine(mineRec,ROW,COL); } /* ------- function defination --------------- */ void initMine(int rec[][COL],int m,int n){ int i,j; for(i=0;i<m;i++) for(j=0;j<n;j++) rec[i][j] = 0; } void initTmp(int rec[][TCOL],int m,int n){ int i,j; for(i=0;i<m;i++) for(j=0;j<n;j++) rec[i][j] = 0; } void showMine(int rec[][COL],int m,int n){ int i,j; for(i=0;i<m;i++){ for(j=0;j<n;j++){ printf("%d ",rec[i][j]); } printf(" "); } printf(" "); } void showTmp(int rec[][TCOL],int m,int n){ int i,j; for(i=0;i<m;i++){ for(j=0;j<n;j++){ printf("%d ",rec[i][j]); } printf(" "); } printf(" "); } void setMine(int rec[][COL],int recTmp[][TCOL],int m,int n){ srand((int)time(0)); int mc = 0; while( mc < MINE_NUM){ int row = rand()%m; int col = rand()%n; if( rec[row][col] != MINE_FLAG ){ rec[row][col] = MINE_FLAG; recTmp[row+1][col+1] = MINE_FLAG; mc++; } } } void sniffeMine(int rec[][COL],int recTmp[][TCOL],int m,int n){ int i,j,row,col; for(i=0;i<m;i++) for(j=0;j<n;j++) if( rec[i][j] != MINE_FLAG ){ row = i+1; col = j+1; rec[i][j] = isMine(recTmp,row-1,col-1) + isMine(recTmp,row-1,col) + isMine(recTmp,row-1,col+1) + isMine(recTmp,row,col-1) + isMine(recTmp,row,col+1) + isMine(recTmp,row+1,col-1) + isMine(recTmp,row+1,col) + isMine(recTmp,row+1,col+1); } } int isMine(int rec[][TCOL],int m,int n){ return rec[m][n] == MINE_FLAG ? 1:0; }
运行结果( 9为雷,其它的为雷的数目):