(挑战编程_1_2)Minesweeper

来源:互联网 发布:外国人怎么开淘宝店 编辑:程序博客网 时间:2024/04/30 01:06

题目链接:http://www.programming-challenges.com/pg.php?page=downloadproblem&probid=110102&format=html

#include <iostream>using namespace std;/*输入char数组、row、column输出扫雷棋盘*/void ReadMine(char mine[][100], int row, int column){for (int i = 0; i < row; ++i){for (int j = 0; j < column; ++j){cin >> mine[i][j];}}}// 定义Mapint map[9][2] = {// 上面三个-1,-1,-1, 0,-1, 1,// 中间三个0, -1,0, 0,0, 1,// 下面三个1, -1,1, 0,1, 1};/*传入i、j,row、col判断是否出界*/bool IsInBoundary(int row, int col, int i, int j){if (i >= 0 && i < row &&j >= 0 && j < col){return true;}return false;}/*输入mine、row、column、i、j输出(i,j)的mine个数计算周围8个位置的mine*/int NumberOfMine(char mine[][100], int row, int column, int i, int j){// 周围雷的个数int num = 0;for (int index = 0; index < 9; ++index){// 新的边界rowint newRow = i + map[index][0];// 新的边界colint newCol = j + map[index][1];// 判断是否出界if (IsInBoundary(row, column, newRow, newCol)){if (mine[newRow][newCol] == '*'){++num;}}}return num;}/*输入棋盘,row、column输出ans*/void CalMine(char mine[][100], int row, int column, char ans[][100]){for (int i = 0; i < row; ++i){for (int j = 0; j < column; ++j){// 如果当前位置是雷if (mine[i][j] == '*'){ans[i][j] = '*';}else{// 将结果转换为char类型ans[i][j] = (char)(NumberOfMine(mine, row, column, i, j) + '0');}}}}/*输入计算过的ans输出扫雷结果*/void PrintMine(char ans[][100], int row, int column, int fieldCount){cout << "Field #" << fieldCount << ":" << endl;//Field #x://printf("Field #%d:\n", fieldCount);for (int i = 0; i < row; ++i){for (int j = 0; j < column; ++j){cout << ans[i][j];}cout << endl;}}int main(){//cout << "MineSweeper" << endl;// 记录处理的总个数,从一开始int fieldCount = 1;// 行数int row = 0;// 列数int column = 0;// 扫雷棋盘,最大行列数不超过100char mine[100][100];// 保存计算结果char ans[100][100];while (cin >> row >> column){// 结束条件if (row == 0 && column == 0){break;}// 读入扫雷棋盘ReadMine(mine, row, column);// 计算扫雷CalMine(mine, row, column, ans);if (fieldCount != 1){cout << endl;}// 打印输出结果PrintMine(ans, row, column, fieldCount++);}}


原创粉丝点击