用两个二维数组,一个是棋盘,一个是被覆盖的棋盘。玩家扫过的地方显示棋盘,没有扫过的地方显示被覆盖的数组。
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<windows.h>
void sch(int a[][16],int i,int j) //初始化棋盘,计算出棋盘上的数字
{
int sum = 0,k,l;
for (k=i-1;k<=i+1;k++)
{
for (l=j-1;l<=j+1;l++)
{
if((((k>=0 && k<16) && (l >= 0 && l<16)) && a[k][l] == -1))
sum ++;
}
}
a[i][j] = sum;
}
void dfs(int a[16][16],char b[16][16],int i,int j) //用深度优先搜索计算出点开的范围
{
if (i<0 || j<0 || i>=16 || j>=16)
return ;
if (a[i][j] != 0 )
{
b[i][j] = '.';
return ;
}
b[i][j] = '.';
if (b[i][j+1]!='.')
dfs(a,b,i,j+1);
if (b[i+1][j]!='.')
dfs(a,b,i+1,j);
if (b[i][j-1]!='.')
dfs(a,b,i,j-1);
if (b[i-1][j]!='.')
dfs(a,b,i-1,j);
if (b[i+1][j+1]!='.')
dfs(a,b,i+1,j+1);
if (b[i+1][j-1]!='.')
dfs(a,b,i+1,j-1);
if (b[i-1][j-1]!='.')
dfs(a,b,i-1,j-1);
if (b[i-1][j+1]!='.')
dfs(a,b,i-1,j+1);
}
int main()
{
int kk,ll,m;
int a[16][16] = {{}},i,j,aa,bb;
int c[16] = {1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6};
char b[16][16] = {{}};
srand((unsigned int)time(NULL));
for (m=0;m<30;m++)
{
kk = rand()%16;
ll = rand()%16;
if (a[kk][ll] == 0)
a[kk][ll] = -1;
else
m--;
}
for(i=0;i<16;i++)
{
for (j=0;j<16;j++)
{
b[i][j] = ',';
if (a[i][j] != -1)
sch(a,i,j);
}
}
while(1)
{
for(i=0;i<16;i++)
{
for (j=0;j<16;j++)
{
if (b[i][j] == '.')
printf("%-2d",a[i][j]);
else
printf("%-2c",b[i][j]);
}
printf(" %d\n",i+1);
}
printf("\n");
for (i=0;i<16;i++)
printf("%-2d",c[i]);
printf("\n");
printf("请输入坐标,如(3-2): ");
scanf("%d-%d",&aa,&bb);
dfs(a,b,aa-1,bb-1);
if (a[aa-1][bb-1] == -1)
{
for(i=0;i<16;i++)
{
for (j=0;j<16;j++)
{
if (b[i][j] == '.' || a[i][j] == -1)
printf("%-2d",a[i][j]);
else
printf("%-2c",b[i][j]);
}
printf("\n");
}
printf("踩到雷了!!\n");
return 0;
}
system("cls"); //清除屏幕上的所有内容
}
return 0;
}