130. Surrounded Regions

题目链接

https://leetcode.com/problems/surrounded-regions/

代码

int dir[4][2] = {
        {0, 1},
        {0, -1},
        {1, 0},
        {-1, 0}
};
class Solution {
public:
    void solve(vector>& board) {
        if (board.size() == 0) {
            return;
        }

        int row = board.size() - 1, col = board[0].size() - 1;

        for (int i = 0; i <= row; ++i) {
            if (board[i][0] == 'O') {
                dfs(board, i, 0, row, col);
            }
            if (board[i][col] == 'O') {
                dfs(board, i, col, row, col);
            }
        }
        for (int i = 0; i <= col; ++i) {
            if (board[0][i] == 'O') {
                dfs(board, 0, i, row, col);
            }
            if (board[row][i] == 'O') {
                dfs(board, row, i, row, col);
            }
        }

        for (int i = 0; i <= row; ++i) {
            for (int j = 0; j <= col; ++j) {
                if (board[i][j] == 'O') {
                    board[i][j] = 'X';
                } else if (board[i][j] == 'S') {
                    board[i][j] = 'O';
                }
            }
        }
    }

    void dfs(vector>& board, int i, int j, int row, int col) {
        board[i][j] = 'S';
        for (int k = 0; k < 4; ++k) {
            int ni = dir[k][0] + i, nj = dir[k][1] + j;
            if (ni >= 0 && ni <= row && nj >= 0 && nj <= col) {
                if (board[ni][nj] == 'O') {
                    dfs(board, ni, nj, row, col);
                }
            }
        }
    }
};

你可能感兴趣的:(130. Surrounded Regions)