提供一个面向过程C/C++代码,很容易用类封装,改成面向对象版本的。
#include
#include
void makeArray(char** &pArray, int row, int col);
void printArray(char** pArray, int row,int col);
void layMines(char** pArray, int row, int col, int num);
void mineHunting(char** pArray, int row, int col, int posX, int posY);
void allMineHunting(char** pArray, int row, int col);
int main() {
char** pArray = nullptr;
int row = 9, col = 9, num=10;
makeArray(pArray,row,col);
layMines(pArray,row,col,num);
allMineHunting(pArray,row,col);
printArray(pArray,row,col);
return 0;
}
void makeArray(char** &pArray, const int row, const int col){
pArray = new char*[row];
for(int i=0;i distribution(0,row*col);
int count =0;
while(count=0&&nX=0&&nY
注意,上面并不是真正的扫雷游戏算法,只是一次性将雷全部探出。真正的扫雷算法是这样的。是有一个DFS的过程在里面的。见Leetcode 529
const int direction[][2] = {{1,1},{1,0},{1,-1},{0,1},{0,-1},{-1,1},{-1,0},{-1,-1}};
class Solution {
public:
void dfs(vector>& board, int x, int y){
if(board[x][y]!='E') return;
int row = board.size(), col = board[0].size();
int count = 0;
for(auto i:direction){
int nx = x + i[0];
int ny = y + i[1];
if(nx>=0&&nx=0&&ny 0){
board[x][y] = '0' + count;
return;
}
board[x][y] = 'B';
for(auto i:direction){
int nx = x + i[0];
int ny = y + i[1];
if(nx>=0&&nx=0&&ny > updateBoard(vector>& board, vector& click) {
int x = click[0], y = click[1];
int row = board.size(), col = board[0].size();
if(board[x][y]=='M'){
board[x][y] = 'X';
return board;
}
dfs(board,click[0],click[1]);
return board;
}
};