关于扫雷的自动补空实现C语言
相信很多朋友在用C语言实现扫雷功能时,都想实现扫雷里面的的自动补足功能,但总是难以实现,在这里我将分享一种方法——递归思想
先看代码!
位置在game.c
//判断附近雷区并过滤空白区(实现递归)
void FilterBlankAreas(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col, int x, int y) {int MineCount = GetMineCount(mine, x, y);if (MineCount != 0) {show[x][y] = MineCount + '0';}else if(show[x][y] != ' ' && MineCount == 0 && x >= 1 && x <= row && y >= 1 && y <= col){show[x][y] = ' ';FilterBlankAreas(mine, show, row, col, x - 1, y - 1);FilterBlankAreas(mine, show, row, col, x - 1, y);FilterBlankAreas(mine, show, row, col, x - 1, y + 1);FilterBlankAreas(mine, show, row, col, x, y - 1);FilterBlankAreas(mine, show, row, col, x, y + 1);FilterBlankAreas(mine, show, row, col, x + 1, y - 1);FilterBlankAreas(mine, show, row, col, x + 1, y);FilterBlankAreas(mine, show, row, col, x + 1, y + 1);}}//排查雷+过滤空白区
void FindMine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col) {int x = 0;int y = 0;while (1) {printf("请输入坐标:");scanf("%d %d", &x, &y);if (x >= 1 && x <= row && y >= 1 && y <= col) {if (mine[x][y] == '1') {printf("很遗憾,你被炸死了!\n");break;}else if (show[x][y] != '*') {DisplayBoard(show, ROW, COL);printf("这个坐标你已经排查过了,请重输\n");}else{FilterBlankAreas(mine, show, row, col, x, y);DisplayBoard(show, ROW, COL);}}else {printf("输入错误,请重输!\n");}}
}
过滤空白区解析
void FilterBlankAreas(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col, int x, int y) {int MineCount = GetMineCount(mine, x, y);if (MineCount != 0) {show[x][y] = MineCount + '0';}else if(show[x][y] != ' ' && MineCount == 0 && x >= 1 && x <= row && y >= 1 && y <= col){show[x][y] = ' ';FilterBlankAreas(mine, show, row, col, x - 1, y - 1);FilterBlankAreas(mine, show, row, col, x - 1, y);FilterBlankAreas(mine, show, row, col, x - 1, y + 1);FilterBlankAreas(mine, show, row, col, x, y - 1);FilterBlankAreas(mine, show, row, col, x, y + 1);FilterBlankAreas(mine, show, row, col, x + 1, y - 1);FilterBlankAreas(mine, show, row, col, x + 1, y);FilterBlankAreas(mine, show, row, col, x + 1, y + 1);}
}
这个FilterBlankAreas()函数主要先判断输入坐标附近八个空间地雷的数量,若地雷的数量不为0,那么直接将show棋盘的该坐标设置为地雷数,并没有进入递归。
反之要是地雷数量为0,那么就进入递归开始排查除了原本x和y的另外8个坐标,注意: 在进入判断递归条件时一定要加入 show[x][y] != ’ ',不然该函数会在内部没有地雷的空间进行无限递归从而导致崩溃。同时还要注意递归的范围是否数组越界,否则会导致严重的问题。
小tip:其实递归函数理论上可以不用八个
FilterBlankAreas(mine, show, row, col, x - 1, y - 1);
FilterBlankAreas(mine, show, row, col, x - 1, y);
FilterBlankAreas(mine, show, row, col, x - 1, y + 1);
FilterBlankAreas(mine, show, row, col, x, y - 1);
FilterBlankAreas(mine, show, row, col, x, y + 1);
FilterBlankAreas(mine, show, row, col, x + 1, y - 1);
FilterBlankAreas(mine, show, row, col, x + 1, y);
FilterBlankAreas(mine, show, row, col, x + 1, y + 1);
用上下左右的坐标再进行递归就可以了,减少了运算量。
FilterBlankAreas(mine, show, row, col, x - 1, y);
FilterBlankAreas(mine, show, row, col, x, y - 1);
FilterBlankAreas(mine, show, row, col, x, y + 1);
FilterBlankAreas(mine, show, row, col, x + 1, y);