-->

Sunday, February 26, 2017

[LeetCode] 529. Minesweeper

https://leetcode.com/contest/leetcode-weekly-contest-21/problems/minesweeper/

Solution:
This question is pretty straightforward. May consider the BSF strategy. (DSF also works, but usually the code length will be a little bit longer for "diffusion" problems in a 2D matrix). Also need a visit matrix to record the visiting status: for each element, if it has been visited(or pushed into a queue), then no more is needed. Without this visit matrix, infinity loop may occur. See code below:

Code:
  1. class Solution {
  2. public:
  3.     vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
  4.         if(board.empty() || board.front().empty()) return board;
  5.         int x=click[0], y=click[1];
  6.         if(board[x][y]=='M'){
  7.             board[x][y]='X';
  8.             return board;
  9.         }
  10.         int m = board.size(), n = board.front().size();
  11.         queue<pair<int, int>> q;
  12.         vector<vector<bool>> visit(m, vector<bool>(n, true));
  13.         q.push(make_pair(x, y));
  14.         visit[x][y]=false;
  15.         vector<vector<int>> d={{0,1},{1,1},{-1,1},{-1,0},{-1,-1},{0,-1},{1,0},{1,-1}};
  16.         while(q.size()){
  17.             pair<int, int> t=q.front();
  18.             q.pop();
  19.             int ct=0;
  20.             for(auto a:d){
  21.                 int tx=t.first+a[0], ty=t.second+a[1];
  22.                 if(tx>=0&&tx<m&&ty>=0&&ty<n){
  23.                     if(board[tx][ty]=='M') ++ct;
  24.                 }
  25.             }
  26.             if(ct==0) {
  27.                 board[t.first][t.second]='B';
  28.                 for(auto a:d){
  29.                     int tx=t.first+a[0], ty=t.second+a[1];
  30.                     if(tx>=0&&tx<m&&ty>=0&&ty<n){
  31.                         if(visit[tx][ty]&&board[tx][ty]=='E') {
  32.                             q.push(make_pair(tx, ty));
  33.                             visit[tx][ty]=false;
  34.                         }
  35.                     }
  36.                 }
  37.             }
  38.             else board[t.first][t.second]=ct+'0';
  39.         }
  40.         return board;
  41.     }
  42. };

No comments :

Post a Comment