时间: 2020-11-23|56次围观|0 条评论

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;
    }
}

 

转载于:https://www.cnblogs.com/goblinengineer/p/5362024.html

原文链接:https://blog.csdn.net/weixin_30342827/article/details/96045799

本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理。

本博客所有文章如无特别注明均为原创。
复制或转载请以超链接形式注明转自起风了,原文地址《lintcode-medium-Surrounded Regions
   

还没有人抢沙发呢~