zoukankan      html  css  js  c++  java
  • LC 529. Minesweeper

    Let's play the minesweeper game (Wikipediaonline game)!

    You are given a 2D char matrix representing the game board. 'M' represents an unrevealed mine, 'E'represents an unrevealed empty square, 'B' represents a revealed blank square that has no adjacent (above, below, left, right, and all 4 diagonals) mines, digit ('1' to '8') represents how many mines are adjacent to this revealed square, and finally 'X' represents a revealed mine.

    Now given the next click position (row and column indices) among all the unrevealed squares ('M' or 'E'), return the board after revealing this position according to the following rules:

    1. If a mine ('M') is revealed, then the game is over - change it to 'X'.
    2. If an empty square ('E') with no adjacent mines is revealed, then change it to revealed blank ('B') and all of its adjacent unrevealed squares should be revealed recursively.
    3. If an empty square ('E') with at least one adjacent mine is revealed, then change it to a digit ('1' to '8') representing the number of adjacent mines.
    4. Return the board when no more squares will be revealed.

    Runtime: 28 ms, faster than 84.38% of C++ online submissions for Minesweeper.

    class Solution {
    public:
      vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
        deque<pair<int,int>> q({ {click[0], click[1]} });
        while(!q.empty()){
          auto c = q.front().first, r = q.front().second, mines = 0;
          vector<pair<int,int>> neighbours;
          if(board[c][r] == 'M') board[c][r] = 'X';
          else for(int i=-1; i<=1; i++){
              for(int j=-1; j<=1; j++){
                if(c+i >= 0 && r+j >= 0 && c+i < board.size() && r+j < board[0].size()){
                  if(board[c+i][r+j] == 'M') ++mines;
                  else if(mines == 0 && board[c+i][r+j] == 'E') neighbours.push_back({c+i,r+j});
                }
              }
            }
          if(mines > 0) board[c][r] = '0' + mines;
          else for(auto n : neighbours) {
            board[n.first][n.second] = 'B';
            q.push_back(n);
          }
          q.pop_front();
        }
        return board;
      }
    };
  • 相关阅读:
    读书笔记之:C语言核心技术
    读书笔记之:C++Primer 第4版(ch111)
    读书笔记之:C与指针
    读书笔记之:C专家编程
    读书笔记之:C/C++代码精髓
    浮点数在内存中的表示
    读书笔记之:C++Primer 第4版(ch1214)
    C/C++语言中const的用法
    比NotePad++更好的文本代码(C#)编辑器Sublime Text
    ExtJs十四(ExtJs Mvc图片管理之四)
  • 原文地址:https://www.cnblogs.com/ethanhong/p/10255316.html
Copyright © 2011-2022 走看看