lintcode-medium-Surrounded Regions

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.

 

Example

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

After capture all regions surrounded by 'X', the board should be:

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


public class Solution {
    /**
     * @param board a 2D board containing 'X' and 'O'
     * @return void
     */
    public void surroundedRegions(char[][] board) {
        // Write your code here
        
        if(board == null || board.length <= 1 || board[0] == null || board[0].length <= 1)
            return;
        
        int m = board.length;
        int n = board[0].length;
        
        for(int i = 0; i < m; i++)
            if(board[i][0] == 'O')
                flood(board, i, 0);
        
        for(int i = 0; i < m; i++)
            if(board[i][n - 1] == 'O')
                flood(board, i, n - 1);
        
        for(int i = 0; i < n; i++)
            if(board[0][i] == 'O')
                flood(board, 0, i);
        
        for(int i = 0; i < n; i++)
            if(board[m - 1][i] == 'O')
                flood(board, m - 1, i);
        
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(board[i][j] == 'O')
                    board[i][j] = 'X';
            }
        }
        
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(board[i][j] == '%')
                    board[i][j] = 'O';
            }
        }
        
        return;
    }
    
    public void flood(char[][] board, int i, int j){
        
        int m = board.length;
        int n = board[0].length;
        
        if(i >= m || i < 0 || j >= n || j < 0)
            return;
        
        if(board[i][j] == 'O'){
            board[i][j] = '%';
            flood(board, i + 1, j);
            flood(board, i - 1, j);
            flood(board, i, j + 1);
            flood(board, i, j - 1);
        }
        
        return;
    }
}

 

posted @ 2016-04-07 07:34  哥布林工程师  阅读(166)  评论(0编辑  收藏  举报