Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's in that surrounded region.
Examples
Input: board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]] Output: [["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]] Explanation: Surrounded regions should not 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.
Input: board = [["X"]] Output: [["X"]]
Constraints
m == board.length
n == board[i].length
1 <= m, n <= 200
board[i][j] is 'X' or 'O'
Java Solution
class Solution {
public void solve(char[][] board) {
if(board == null || board.length == 0) return;
List<Pair<Integer, Integer>> borders = new LinkedList<Pair<Integer,Integer>>();
for(int i = 0; i < board.length; i++) {
borders.add(new Pair(i, 0));
borders.add(new Pair(i, board[0].length - 1));
}
for(int i = 0; i < board[0].length; i++) {
borders.add(new Pair(0,i));
borders.add(new Pair(board.length - 1, i));
}
for(Pair<Integer, Integer> pair : borders) {
dfs(board, pair.first, pair.second);
}
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[0].length; j++) {
if(board[i][j] == 'O') board[i][j] = 'X';
if(board[i][j] == 'E') board[i][j] = 'O';
}
}
}
private void dfs(char[][] board, int row, int col) {
if(board[row][col] != 'O') return;
board[row][col] = 'E';
if(col < board[0].length - 1) dfs(board, row, col+1);
if(col > 0) dfs(board, row, col - 1);
if(row < board.length - 1) dfs(board, row + 1, col);
if(row > 0) dfs(board, row - 1, col);
}
}
class Pair<U,V> {
public U first;
public V second;
public Pair(U first, V second) {
this.first = first;
this.second = second;
}
}