• 529. Minesweeper


    class Solution {
        
        unordered_set<string> visited;
        
        inline string hash(int r, int c) {
            return to_string(r) + "#" + to_string(c);
        }
        
        void check(vector<vector<char>>& board, 
                   int row, 
                   int col,
                   vector<vector<int>>& blocks,
                   int& mines) {
            
            int width = board[0].size();
            int height = board.size();
            
            int dirs[] = {
                //left
                -1, 0,
                //right
                1, 0,
                //up
                0, -1,
                //down
                0, 1,
                //topleft
                -1, -1,
                //topright
                1, -1,
                //bottomleft
                -1, 1,
                //bottomright
                1, 1
            };
            
            for (int i = 0; i < 8; ++i) {
                int dr = row + dirs[2*i];
                int dc = col + dirs[2*i + 1];
                if (dr < 0 || dr > height - 1 || dc < 0 || dc > width - 1) {
                    continue;
                }
                
                if (board[dr][dc] == 'M') {
                    mines++;
                }
                else if (board[dr][dc] == 'E') {
                    blocks.push_back({dr, dc});
                }
            }
            
        }
        
        void reveal(vector<vector<char>>& board, int row, int col) {
            auto key = hash(row, col);
            if (visited.find(key) != visited.end()) return;
            visited.insert(key);
            
            vector<vector<int>> blocks;
            int mineCount = 0;
            check(board, row, col, blocks, mineCount);
            
            if (mineCount > 0) {
                board[row][col] = '0' + mineCount;
                return;
            }
            
            board[row][col] = 'B';
            
            for (auto& b : blocks) {
                reveal(board, b[0], b[1]);
            }
        }
    public:
        vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
            int row = click[0];
            int col = click[1];
            
            if (board[row][col] == 'M') {
                board[row][col] = 'X';
                return board;
            }
            
            reveal(board, row, col);
            return board;
        }
    };
  • 相关阅读:
    markdown语法及工具
    关于div的宽度或高度设置为100%时
    响应式css垂直居中
    JavaScript之闭包问题以及立即执行函数
    JavaScript和JQuery好书推荐
    数组中去重
    解决getImageData跨域问题
    js在for循环中绑定事件
    表格横竖颠倒
    上传按钮美化遇到的问题
  • 原文地址:https://www.cnblogs.com/agentgamer/p/11215623.html
Copyright © 2020-2023  润新知