Skip to content

Instantly share code, notes, and snippets.

@guolinaileen
Last active December 14, 2015 22:09
Show Gist options
  • Save guolinaileen/5156640 to your computer and use it in GitHub Desktop.
Save guolinaileen/5156640 to your computer and use it in GitHub Desktop.
Java is too slow to pass the large test.
public class Solution {
public void solve(char[][] board) {
// Start typing your Java solution below
// DO NOT write main() function
if( board==null || board.length==0 || board[0].length==0) return;
int m=board.length;
int n=board[0].length;
for(int i=0; i<m; i++)
{
if(board[i][0]=='O') DFS(board, i, 0);
if(board[i][n-1]=='O') DFS(board, i, n-1);
}
for(int j=1; j<n-1; j++)
{
if(board[0][j]=='O') DFS(board, 0, j);
if(board[m-1][j]=='O') DFS(board, m-1, j);
}
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
if(board[i][j]=='O') board[i][j]='X';
if(board[i][j]=='D') board[i][j]='O';
}
}
}
void DFS(char [][] board, int i, int j)
{
board[i][j]='D';
if(i+1<board.length && board[i+1][j]=='O') DFS(board, i+1, j);
if(i-1>=0 && board[i-1][j]=='O') DFS(board, i-1, j);
if(j+1<board[0].length && board[i][j+1]=='O') DFS(board, i, j+1);
if(j-1>=0 && board[i][j-1]=='O') DFS(board, i, j-1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment