用c语言写一个扫雷求解问题的代码
时间: 2023-03-28 11:03:07 浏览: 102
可以的,我可以回答这个问题。以下是一个简单的扫雷求解问题的代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 10
#define COLS 10
#define MINES 10
void init_board(int board[ROWS][COLS], int rows, int cols, int mines);
void print_board(int board[ROWS][COLS], int rows, int cols);
int count_mines(int board[ROWS][COLS], int row, int col);
int main(void) {
int board[ROWS][COLS];
int row, col;
srand(time(NULL));
init_board(board, ROWS, COLS, MINES);
print_board(board, ROWS, COLS);
printf("Enter row and column to check: ");
scanf("%d %d", &row, &col);
if (board[row][col] == -1) {
printf("BOOM! You hit a mine.\n");
} else {
printf("There are %d mines nearby.\n", count_mines(board, row, col));
}
return ;
}
void init_board(int board[ROWS][COLS], int rows, int cols, int mines) {
int i, j, count;
for (i = ; i < rows; i++) {
for (j = ; j < cols; j++) {
board[i][j] = ;
}
}
count = ;
while (count < mines) {
i = rand() % rows;
j = rand() % cols;
if (board[i][j] == ) {
board[i][j] = -1;
count++;
}
}
}
void print_board(int board[ROWS][COLS], int rows, int cols) {
int i, j;
printf(" ");
for (j = ; j < cols; j++) {
printf("%2d ", j);
}
printf("\n");
printf(" +");
for (j = ; j < cols; j++) {
printf("---");
}
printf("\n");
for (i = ; i < rows; i++) {
printf("%2d|", i);
for (j = ; j < cols; j++) {
if (board[i][j] == -1) {
printf(" * ");
} else {
printf(" %d ", count_mines(board, i, j));
}
}
printf("\n");
}
printf(" +");
for (j = ; j < cols; j++) {
printf("---");
}
printf("\n");
}
int count_mines(int board[ROWS][COLS], int row, int col) {
int i, j, count;
count = ;
for (i = row - 1; i <= row + 1; i++) {
for (j = col - 1; j <= col + 1; j++) {
if (i >= && i < ROWS && j >= && j < COLS && board[i][j] == -1) {
count++;
}
}
}
return count;
}
阅读全文