Time Cost

26min45s

Implementation

First push all ‘O’ on edge in a queue. Then use DFS to deal with O in the queue.

Code

  • Solution
    class Solution {
    public:
      void solve(vector<vector<char>>& board) {
          int m = board.size();
          if (m == 0) return;
          int n = board[0].size();
          if (n == 0) return;
    
          queue<pair<int,int>> q;
    
          auto push_if_O = [&](int x, int y) {
              if (board[x][y] == 'O') {
                  board[x][y] = 'E';         
                  q.push({x, y});
              }
          };
    
          for (int i = 0; i < m; i++) {
              push_if_O(i, 0);
              push_if_O(i, n - 1);
          }
          for (int j = 0; j < n; j++) {
              push_if_O(0, j);
              push_if_O(m - 1, j);
          }
    
          static const int dx[4] = {1, -1, 0, 0};
          static const int dy[4] = {0, 0, 1, -1};
    
          while (!q.empty()) {
              auto [x, y] = q.front();
              q.pop();
              for (int k = 0; k < 4; k++) {
                  int nx = x + dx[k], ny = y + dy[k];
                  if (0 <= nx && nx < m && 0 <= ny && ny < n && board[nx][ny] == 'O') {
                      board[nx][ny] = 'E';
                      q.push({nx, ny});
                  }
              }
          }
    
          for (int i = 0; i < m; i++) {
              for (int j = 0; j < n; j++) {
                  if (board[i][j] == 'O') board[i][j] = 'X';
                  else if (board[i][j] == 'E') board[i][j] = 'O';
              }
          }
      }
    };