Minesweeper [LeetCode 529]

来源:互联网 发布:淘宝手机宝贝链接在哪 编辑:程序博客网 时间:2024/04/30 01:07

Answer


#include <vector>#include <iostream>using namespace std;class Solution {public:    vector<vector<char> > updateBoard(vector<vector<char> >& board, vector<int>& click) {        if (board[click[0]][click[1]] == 'M') {            board[click[0]][click[1]] = 'X';            return board;        }        reveal(board, click[0], click[1]);        return board;    }    bool inBoard(vector<vector<char> >& board, int x, int y) {        return (x >= 0 && x < board.size()) && (y >= 0 && y < board[0].size());    }    void reveal(vector<vector<char> >& board, int x, int y) {        if (!inBoard(board, x, y)) {            return;        }        if (board [x][y] == 'E') {            int num = 0;            if (inBoard(board, x - 1, y - 1) && board[x - 1][y - 1] == 'M') num++;            if (inBoard(board, x - 1, y) && board[x - 1][y] == 'M') num++;            if (inBoard(board, x - 1, y + 1) && board[x - 1][y + 1] == 'M') num++;            if (inBoard(board, x, y - 1) && board[x][y - 1] == 'M') num++;            if (inBoard(board, x, y + 1) && board[x][y + 1] == 'M') num++;            if (inBoard(board, x + 1, y - 1) && board[x + 1][y - 1] == 'M') num++;            if (inBoard(board, x + 1, y) && board[x + 1][y] == 'M') num++;            if (inBoard(board, x + 1, y + 1) && board[x + 1][y + 1] == 'M') num++;            if (num > 0)  {                board[x][y] = '0' + num;            } else {                board[x][y] = 'B';                reveal(board, x - 1, y - 1);                reveal(board, x - 1, y);                reveal(board, x - 1, y + 1);                reveal(board, x, y - 1);                reveal(board, x, y + 1);                reveal(board, x + 1, y - 1);                reveal(board, x + 1, y);                reveal(board, x + 1, y + 1);            }        }        // cout << x << ' ' << y <<' ' <<board[x][y] << endl;        // for (int i = 0; i < 3; i++) {        // for (int j = 0; j < 5; j++) {        //     cout << i << ' '<<  j << ' ' << board[i][j] << ' ';        // }        // cout << endl;        // }    }};int main() {    char aa[5] = {'E','E','E','E','E'};    char bb[5] = {'E','E','M','E','E'};    vector<char> aa1(aa, aa + 5);    vector<char> bb1(bb, bb + 5);    vector<vector<char> > a;    a.push_back(aa1);    a.push_back(bb1);    a.push_back(aa1);    a.push_back(aa1);    // for (int i = 0; i < 5; i++) {    //     for (int j = 0; j < 5; j++) {    //         cout << a[i][j] << ' ';    //     }    //     cout << endl;    // }    vector<int> b;    b.push_back(3);    b.push_back(0);    //cout << a.size() << ' ' << a[0].size();    Solution temp;    temp.updateBoard(a, b);    for (int i = 0; i < 3; i++) {        for (int j = 0; j < 5; j++) {            cout << a[i][j] << ' ';        }        cout << endl;    }}
原创粉丝点击