solution.cpp 1.2 KB
Newer Older
每日一练社区's avatar
每日一练社区 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
class Solution
{
public:
    int dx[4] = {0, 0, 1, -1}, dy[4] = {1, -1, 0, 0}, n, m;
    void dfs(int row, int col, vector<vector<char>> &board)
    {
        board[row][col] = 'o';
        for (int i = 0; i < 4; ++i)
            if (row + dx[i] >= 0 && row + dx[i] < n && col + dy[i] >= 0 && col + dy[i] < m && board[row + dx[i]][col + dy[i]] == 'O')
                dfs(row + dx[i], col + dy[i], board);
    }
    void solve(vector<vector<char>> &board)
    {
        n = board.size(), m = n ? board[0].size() : 0;
        if (!(m & n))
            return;
        for (int i = 0; i < n; ++i)
        {
            if (board[i][0] == 'O')
                dfs(i, 0, board);
            if (board[i][m - 1] == 'O')
                dfs(i, m - 1, board);
        }
        for (int j = 0; j < m; ++j)
        {
            if (board[0][j] == 'O')
                dfs(0, j, board);
            if (board[n - 1][j] == 'O')
                dfs(n - 1, j, board);
        }
        for (int i = 0; i < n; ++i)
            for (int j = 0; j < m; ++j)
                if (board[i][j] == 'O')
                    board[i][j] = 'X';
                else if (board[i][j] == 'o')
                    board[i][j] = 'O';
    }
};