Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Last active December 20, 2015 22:39
Show Gist options
  • Save charlespunk/6206430 to your computer and use it in GitHub Desktop.
Save charlespunk/6206430 to your computer and use it in GitHub Desktop.
Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's in that surrounded region .
For 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
public class Solution {
public void solve(char[][] board) {
// Start typing your Java solution below
// DO NOT write main() function
if(board == null || board.length < 1 || board[0].length < 1) return;
findLive(board);
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';
else if(board[i][j] == 'F') board[i][j] = 'O';
}
}
}
public void findLive(char[][] board){
for(int colum = 0; colum < board[0].length; colum++) search(0, colum, board);
for(int row = 1; row < board.length - 1; row++) search(row, board[0].length - 1, board);
for(int colum = 1; colum < board[0].length; colum++) search(board.length - 1, colum, board);
for(int row = 1; row < board.length; row++) search(row, 0, board);
}
public void search(int row, int colum, char[][] board){
if(row < 0 || row >= board.length || colum < 0 || colum >= board[0].length
||board[row][colum] != 'O') return;
board[row][colum] = 'F';
search(row - 1, colum, board);
search(row + 1, colum, board);
search(row, colum - 1, board);
search(row, colum + 1, board);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment