Posted on

Description

Submission

class Solution {
    int m, n;
    vector<int> dirs;
    void dfs(vector<vector<char>>& board, int x, int y) {
        board[x][y] = 'O';

        for(int k = 0; k < 4; ++k) {
            int x2 = x + dirs[k];
            int y2 = y + dirs[k+1];
            if(x2 < 0 || y2 < 0 || x2 >= m || y2 >= n || board[x2][y2] != 'T') continue;
            dfs(board, x2, y2);
        }
    }

public:
    void solve(vector<vector<char>>& board) {
        m = board.size();
        n = board[0].size();

        dirs = {-1, 0, 1, 0, -1};

        for(int i = 0; i < m; ++i) {
            for(int j = 0; j < n; ++j) {
                if(board[i][j] == 'O') board[i][j] = 'T';
            }
        }

        for(int i = 0; i < m; ++i) {
            if(board[i][0] == 'T') dfs(board, i, 0);
            if(board[i][n-1] == 'T') dfs(board, i, n-1);
        }

        for(int i = 0; i < n; ++i) {
            if(board[0][i] == 'T') dfs(board, 0, i);
            if(board[m-1][i] == 'T') dfs(board, m-1, i);
        }

        for(int i = 0; i < m; ++i) {
            for(int j = 0; j < n; ++j) {
                if(board[i][j] == 'T') board[i][j] = 'X';
            }
        }
    }
};

// [["O","X","X","O","X"],
//  ["X","O","O","X","O"],
//  ["X","O","X","O","X"],
//  ["O","X","O","O","O"],
//  ["X","X","O","X","O"]]

Leave a Reply

Your email address will not be published. Required fields are marked *