130. Surrounded Regions

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:

X X X X
X O O X
X X O X
X O X X

After running your function, the board should be:

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.

Rust Solution

struct Solution;

impl Solution {
    fn solve(board: &mut Vec<Vec<char>>) {
        let n = board.len();
        if n == 0 {
            return;
        }
        let m = board[0].len();
        let mut visited = vec![vec![false; m]; n];
        for i in 0..n {
            for j in 0..m {
                if i == 0 || j == 0 || i == n - 1 || j == m - 1 {
                    if board[i][j] == 'O' && !visited[i][j] {
                        Self::dfs(i, j, &mut visited, board, n, m);
                    }
                }
            }
        }
        for i in 0..n {
            for j in 0..m {
                if !visited[i][j] {
                    board[i][j] = 'X';
                }
            }
        }
    }

    fn dfs(i: usize, j: usize, visited: &mut [Vec<bool>], board: &[Vec<char>], n: usize, m: usize) {
        visited[i][j] = true;
        if i > 0 && !visited[i - 1][j] && board[i - 1][j] == 'O' {
            Self::dfs(i - 1, j, visited, board, n, m);
        }
        if j > 0 && !visited[i][j - 1] && board[i][j - 1] == 'O' {
            Self::dfs(i, j - 1, visited, board, n, m);
        }
        if i + 1 < n && !visited[i + 1][j] && board[i + 1][j] == 'O' {
            Self::dfs(i + 1, j, visited, board, n, m);
        }
        if j + 1 < m && !visited[i][j + 1] && board[i][j + 1] == 'O' {
            Self::dfs(i, j + 1, visited, board, n, m);
        }
    }
}

#[test]
fn test() {
    let mut board = vec_vec_char![
        ['X', 'X', 'X', 'X'],
        ['X', 'O', 'O', 'X'],
        ['X', 'X', 'O', 'X'],
        ['X', 'O', 'X', 'X']
    ];
    let res = vec_vec_char![
        ['X', 'X', 'X', 'X'],
        ['X', 'X', 'X', 'X'],
        ['X', 'X', 'X', 'X'],
        ['X', 'O', 'X', 'X']
    ];
    Solution::solve(&mut board);
    assert_eq!(board, res);
}

Having problems with this solution? Click here to submit an issue on github.