Surrounded Regions

解题思路

DFS

代码

class Solution {
public:
    void solve(vector<vector<char>>& board) {
        if (board.size() < 1 || board[0].empty()) {
            return;
        }
        int m = board.size();
        int n = board[0].size();
        for (int i = 0; i < m; ++i) {
            if (board[i][0] == 'O') {
                link(board, i, 0);
            }
            if (board[i][n-1] == 'O') {
                link(board, i, n-1);
            } 
        }
        for (int i = 0; i < n; ++i) {
            if (board[0][i] == 'O') {
                link(board, 0, i);
            }
            if (board[m-1][i] == 'O') {
                link(board, m-1, i);
            }
        }
        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] == 'J') {
                    board[i][j] = 'O';
                }
            }
        }
    }
    
    void link(vector<vector<char>>& board, int x, int y) {
        board[x][y] = 'J';
        int m = board.size();
        int n = board[0].size();
        if (y > 0 && board[x][y-1] == 'O') {
            link(board, x, y-1);
        }
        if (y < (n-1) && board[x][y+1] == 'O') {
            link(board, x, y+1);
        }
        if (x > 0 && board[x-1][y] == 'O') {
            link(board, x-1, y);
        }
        if (x < (m-1) && board[x+1][y] == 'O') {
            link(board, x+1, y);
        }
    }
};