题目
让我们一起来玩扫雷游戏!
给定一个代表游戏板的二维字符矩阵。 ‘M’ 代表一个未挖出的地雷,‘E’ 代表一个未挖出的空方块,‘B’ 代表没有相邻(上,下,左,右,和所有4个对角线)地雷的已挖出的空白方块,数字(‘1’ 到 ‘8’)表示有多少地雷与这块已挖出的方块相邻,‘X’ 则表示一个已挖出的地雷。
现在给出在所有未挖出的方块中(‘M’或者’E’)的下一个点击位置(行和列索引),根据以下规则,返回相应位置被点击后对应的面板:
示例1
输入:
[[‘E’, ‘E’, ‘E’, ‘E’, ‘E’],
[‘E’, ‘E’, ‘M’, ‘E’, ‘E’],
[‘E’, ‘E’, ‘E’, ‘E’, ‘E’],
[‘E’, ‘E’, ‘E’, ‘E’, ‘E’]]
Click : [3,0]
输出:
[[‘B’, ‘1’, ‘E’, ‘1’, ‘B’],
[‘B’, ‘1’, ‘M’, ‘1’, ‘B’],
[‘B’, ‘1’, ‘1’, ‘1’, ‘B’],
[‘B’, ‘B’, ‘B’, ‘B’, ‘B’]]
示例2
输入:
[[‘B’, ‘1’, ‘E’, ‘1’, ‘B’],
[‘B’, ‘1’, ‘M’, ‘1’, ‘B’],
[‘B’, ‘1’, ‘1’, ‘1’, ‘B’],
[‘B’, ‘B’, ‘B’, ‘B’, ‘B’]]
Click : [1,2]
输出:
[[‘B’, ‘1’, ‘E’, ‘1’, ‘B’],
[‘B’, ‘1’, ‘X’, ‘1’, ‘B’],
[‘B’, ‘1’, ‘1’, ‘1’, ‘B’],
[‘B’, ‘B’, ‘B’, ‘B’, ‘B’]]
注意
解法
代码
#include
#include
#include
#include
using namespace std;
class Solution {
public:
int dx[8] = {0, 1, 0, -1, 1, 1, -1, -1};
int dy[8] = {1, 0, -1, 0, 1, -1, 1, -1};
vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
int x = click[0], y = click[1];
if (board[x][y] == 'M') {
board[x][y] = 'X';
} else {
bfs(board,click);
}
return board;
}
void bfs(vector<vector<char>>& board, vector<int>& click) {
queue<pair<int, int>> q;
vector<vector<int>> vist(board.size(),vector<int>(board[0].size(),0));
q.push({click[0],click[1]});
vist[click[0]][click[1]] = 1;
while(!q.empty()){
pair<int, int> tmp = q.front();
q.pop();
int x = tmp.first,y = tmp.second;
int cnt = 0;
for(int i=0;i<8;i++){
int tx = x + dx[i];
int ty = y + dy[i];
if (tx >=0 && tx < board.size() && ty >= 0 && ty < board[0].size() && board[tx][ty]=='M') {
cnt++;
}
}
if(cnt>0)
board[x][y] =cnt+'0';
else{
board[x][y] = 'B';
for (int i = 0; i < 8; ++i) {
int tx = x + dx[i];
int ty = y + dy[i];
if (tx >=0 && tx < board.size() && ty >= 0 && ty < board[0].size() && board[tx][ty]=='E' && vist[tx][ty]==0)
{
q.push({tx,ty});
vist[tx][ty] = 1;
}
}
}
}
}
};
int main()
{
vector<vector<char>> board(4,vector<char>(5));
for(int i=0;i<board.size();i++)
for(int j=0;j<board[i].size();j++)
board[i][j] = 'E';
board[1][2] = 'M';
vector<int> click(2);
click[0] = 3;
click[1] = 0;
Solution s;
vector<vector<char>> upboard = s.updateBoard(board, click);
for(int i=0;i<board.size();i++){
for(int j=0;j<board[i].size();j++)
cout<<upboard[i][j];
cout<<endl;
}
return 0;
}
今天也是爱zz的一天哦!