[LeetCode] 130. Surrounded Regions

Problem

Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.

A region is captured by flipping all 'O's into 'X's in that surrounded region.

Example:

1
2
3
4
X X X X
X O O X
X X O X
X O X X

After running your function, the board should be:

1
2
3
4
X X X X
X X X X
X X X X
X O X X

Explanation

Surrounded regions shouldn’t be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically.

Explanation

  1. First, we can find the boarder’s character, if they are ‘O’, then we flood fill them to ‘Y’.
  2. Next, we can replace the rest of ‘O’ to be ‘X’ since they are not connected to the boarder.
  3. Finally, replace all ‘Y’ back to ‘O’.

Solution

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Solution {
    void fillBoarders(char[][] board, char target, char c) {
        int row = board.length, col = board[0].length;

        //check most left and most right column
        for (int ro = 0; ro < row; ro++) {
            if (board[ro][0] == target) {
                fill(board, ro, 0, target, c);
            }
            if (board[ro][col-1] == target) {
                fill(board, ro, col-1, target, c);
            }
        }

        // check first row and last row
        for (int co = 0; co < col; co++) {
            if (board[0][co] == target) {
                fill(board, 0, co, target, c);
            }
            if (board[row-1][co] == target) {
                fill(board, row-1, co, target, c);
            }
        }
    }

    void fill(char[][] board, int row, int col, char target, char c) {
        if (row < 0 || row >= board.length || col < 0 || col >= board[0].length) return;
        if (board[row][col] != target) return;
        board[row][col] = c;
        fill(board, row-1, col, target, c);
        fill(board, row+1, col, target, c);
        fill(board, row, col-1, target, c);
        fill(board, row, col+1, target, c);
    }

    void replace(char[][] board, char target, char ch) {
        int row = board.length, col = board[0].length;
        for (int r = 0; r < row; r++) {
            for (int c = 0; c < col; c++) {
                if (board[r][c] == target) {
                    board[r][c] = ch;
                }
            }
        }
    }

    public void solve(char[][] board) {
        if (board == null || board.length < 3 || board[0].length < 3) return;
        fillBoarders(board, 'O', 'Y');
        replace(board, 'O', 'X');
        replace(board, 'Y', 'O');
    }
}