php扫雷算法,扫雷游戏算法 - osc_qv1fwke0的个人空间 - OSCHINA - 中文开源技术交流社区...

提供一个面向过程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

pArray[i] = new char[col];

}

for(int i=0;i

for(int j=0;j

pArray[i][j] = '0';

}

}

}

void printArray(char** pArray,int row,int col){

for(int i=0;i

for(int j=0;j

std::cout<

}

std::cout<<:endl>

}

}

void layMines(char** pArray,int row,int col, int num){

std::random_device generator;

std::uniform_int_distribution distribution(0,row*col);

int count =0;

while(count

int dice_roll = distribution(generator);

int i = dice_roll/row;

int j = dice_roll%col;

if(pArray[i][j]!='9'){

pArray[i][j]='9';

count++;

}

}

}

void mineHunting(char** pArray, int row, int col, int posX, int posY){

if(pArray[posX][posY]!='0') return;

int count = 0;

const int direction[][2] = {{1,1},{1,0},{1,-1},{0,1},{0,-1},{-1,1},{-1,0},{-1,-1}};

for(auto i : direction){

int nX = posX + i[0];

int nY = posY + i[1];

if(nX>=0&&nX=0&&nY

}

pArray[posX][posY] = char('0' + count);

}

void allMineHunting(char** pArray, int row, int col){

for(int i=0;i

for(int j=0;j

mineHunting(pArray,row,col,i,j);

}

}

}

注意,上面并不是真正的扫雷游戏算法,只是一次性将雷全部探出。真正的扫雷算法是这样的。是有一个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

}

if(count>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

dfs(board,nx,ny);

}

}

}

vector> 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;

}

};

你可能感兴趣的:(php扫雷算法)