?LeetCode刷題實(shí)戰(zhàn)529:掃雷游戲


示例? ? ? ? ? ? ? ? ? ? ? ? ?

解題

class?Solution?{
public:
????int?dir_x[8] = {0, 1, 0, -1, 1, 1, -1, -1};
????int?dir_y[8] = {1, 0, -1, 0, 1, -1, 1, -1};
?
????void?dfs(vector<vector<char>>& board, int?x, int?y)?{
????????int?cnt = 0;
????????for?(int?i = 0; i < 8; ++i) {
????????????int?tx = x + dir_x[i];
????????????int?ty = y + dir_y[i];
????????????if?(tx < 0?|| tx >= board.size() || ty < 0?|| ty >= board[0].size()) {
????????????????continue;
????????????}
????????????// 不用判斷 M,因?yàn)槿绻?M 的話游戲已經(jīng)結(jié)束了
????????????cnt += board[tx][ty] == 'M';
????????}
????????if?(cnt > 0) {
????????????// 規(guī)則 3
????????????board[x][y] = cnt + '0';
????????} else?{
????????????// 規(guī)則 2
????????????board[x][y] = 'B';
????????????for?(int?i = 0; i < 8; ++i) {
????????????????int?tx = x + dir_x[i];
????????????????int?ty = y + dir_y[i];
????????????????// 這里不需要在存在 B 的時(shí)候繼續(xù)擴(kuò)展,因?yàn)?B 之前被點(diǎn)擊的時(shí)候已經(jīng)被擴(kuò)展過(guò)了
????????????????if?(tx < 0?|| tx >= board.size() || ty < 0?|| ty >= board[0].size() || board[tx][ty] != 'E') {
????????????????????continue;
????????????????}
????????????????dfs(board, tx, ty);
????????????}
????????}
????}
?
????vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
????????int?x = click[0], y = click[1];
????????if?(board[x][y] == 'M') {
????????????// 規(guī)則 1
????????????board[x][y] = 'X';
????????} else?{
????????????dfs(board, x, y);
????????}
????????return?board;
????}
};
