130. Surrounded Regions
public class Solution { public void solve(char[][] board) { if (board.length == 0 || board[0].length == 0) return; int m = board.length; int n = board[0].length; boolean[][] visited = new boolean[m][n]; for (int j = 0; j < n; j ++) { if (board[0][j] == 'O') fill(0,j,board,visited); if (board[m-1][j] == 'O') fill(m-1,j,board,visited); } for (int i = 0; i < m; i++) { if (board[i][0] == 'O') fill(i,0,board,visited); if (board[i][n-1] == 'O') fill(i,n-1,board,visited); } for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) if (visited[i][j] == false&&board[i][j] == 'O') board[i][j] = 'X'; } private void fill(int i, int j, char[][] board, boolean[][] visited) { if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || visited[i][j] == true || board[i][j] == 'X') return; visited[i][j] = true; if(i > 1) fill(i-1,j,board,visited); if (i < board.length - 2) fill(i+1,j,board,visited); if (j > 1) fill(i,j-1,board,visited); if (j < board[0].length-2) fill(i,j+1,board,visited); } }