[LintCode] Surrounded Regions

java 4 2016-02-29 13:03
女装

Problem

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

Solution

public class Solution {
    public void surroundedRegions(char[][] board) {
        // Write your code here
        if (board == null || board.length < 2 || board[0].length < 2) return;
        int m = board.length;
        int n = board[0].length;
        //先用bfs处理左右边界上的'O'(换成'#')
        for (int i = 0; i < m; i++) {
            if (board[i][0] == 'O') {
                bfs(board, i, 0);
            }
            if (board[i][n-1] == 'O') {
                bfs(board, i, n-1);
            }
        }
        //再用bfs处理上下边界(除去四角)的'O'(换成'#')
        for (int i = 1; i < n-1; i++) {
            if (board[0][i] == 'O') {
                bfs(board, 0, i);
            }
            if (board[m-1][i] == 'O') {
                bfs(board, m-1, i);
            }
        }
        //把剩下的没有被处理过,也就是被包围的'O'置为'X'
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j] == 'O') {
                    board[i][j] = 'X';
                }
            }
        }
        //把所有暂时置为'#'的不被包围的'O'换回'O'
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j] == '#') {
                    board[i][j] = 'O';
                }
            }
        }
    }
    public void bfs(char[][] board, int row, int col) {
        //如当前字符的坐标越界or不是'O',返回
        if (row < 0 || row >= board.length || col < 0 || col >= board[0].length || board[row][col] != 'O') {
            return;
        }
        //是'O'的都置为'#',然后迭代其上下左右各点
        board[row][col] = '#';
        bfs(board, row-1, col);
        bfs(board, row+1, col);
        bfs(board, row, col-1);
        bfs(board, row, col+1);
    }
}
女装
文章评论