下面是一个部分解决方案,它留下了一些部分作为 OP 的练习。
#include <stdio.h>
#include <stdlib.h>
#define BOARD_SIZE 8
int main(void) {
FILE *fp;
fp = fopen("mines.in","r");
if ( fp == NULL ) {
fprintf(stderr,"Could not open file\n");
return 1;
}
int nBoards = 0;
int nMines = 0;
int col;
int row;
int currentBoard = 0;
/* We know the first row is going to be the number of boards */
fscanf(fp,"%d",&nBoards);
printf("We have %d boards\n",nBoards);
while ( fscanf(fp,"%d",&nMines) > 0 ) {
int i,j;
/* initialize board as all zeros */
int board[BOARD_SIZE][BOARD_SIZE] = { {0} };
currentBoard++;
printf("Board %d:\n",currentBoard);
/* Read in and set the mines */
for (i=0; i<nMines; i++) {
fscanf(fp,"%d %d",&col,&row);
board[col-1][row-1] = 9;
}
/* Add mine proximity */
for (i=0; i<BOARD_SIZE; i++) {
for (j=0; j<BOARD_SIZE; j++) {
if ( board[i][j] == 9 ) { /* we have a mine */
/* Square to the left */
if (j > 0 && board[i][j-1] != 9) {
board[i][j-1]++;
}
/* Square to the right */
/* Left as exercise for the OP*/
/* Square above */
/* Left as exercise for the OP*/
/* Square below */
/* Left as exercise for the OP*/
}
}
/* Print out the board */
for (i=0; i<BOARD_SIZE; i++) {
for (j=0; j<BOARD_SIZE; j++) {
printf("%d ",board[i][j]);
}
printf("\n");
}
printf("\n");
}
fclose(fp);
if (currentBoard != nBoards) {
fprintf(stderr,"Expected %d boards, read in %d boards\n",nBoards,currentBoard);
return 1;
}
return 0;
}
代码读取第一行以记录板的数量,然后循环遍历包含地雷数量和地雷位置的数据块。while
循环将在包含地雷数量的行上执行,fscanf
并且在 while 循环的主体中,不同的地雷位置将被读入为棋盘定义的数字。
一旦我们有了所有的地雷位置,我们就可以计算板上其他方格中的数字,我在代码中只显示了其中一个(其他方格类似)。
请注意,上面的代码几乎没有错误处理,也几乎没有对输入文件进行验证——如果输入文件错误,您可能会收到错误,即对数组的“超出范围”访问。我省略了这些检查以使程序的底层逻辑更清晰。
另请注意,我假设输入索引是“1”索引(即在 [1,8] 范围内,而不是 C 期望的“0”索引(即在 [0,7] 范围内),因此行中 1 的替换board[col-1][row-1] = 9;
。