LeetCode-130 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.

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

思路: 将已知不被包围的“O”置为"P",并将“P”四周为“O”的位置也置为“P”,用一个队列记录当前遍历过的“P”的坐标。
初始时,扫描第一行,最后一行,第一列,最后一列并记录为“O”的位置。
代码如下:
public void solve(char[][] board) {
        List<Pos> list = new ArrayList<Pos>();
        if(board == null || board.length == 0)
            return;
        
        for(int i=0; i<board[0].length;i++) {
            if(board[0][i] == 'O') {
                board[0][i] = 'P';
                list.add(new Pos(0, i));
            }
            if(board[board.length-1][i] == 'O') {
                board[board.length-1][i] = 'P';
                list.add(new Pos(board.length-1, i)); 
            }
        }
        
        for(int i=0; i<board.length;i++) {
            if(board[i][0] == 'O') {
                board[i][0] = 'P';
                list.add(new Pos(i,0));
            }
            if(board[i][board[0].length-1] == 'O') {
                board[i][board[0].length-1] = 'P';
                list.add(new Pos(i, board[0].length-1));
            }
        }
        
        
        while(!list.isEmpty()) {
            Pos current = list.remove(0);
            if(current.row > 0 && board[current.row-1][current.col] == 'O') {
                board[current.row-1][current.col] = 'P';
                list.add(new Pos(current.row-1,current.col));
            }
            if(current.row < board.length-1 && board[current.row+1][current.col] == 'O') {
                board[current.row+1][current.col] = 'P';
                list.add(new Pos(current.row+1,current.col));
            }
            if(current.col > 0 && board[current.row][current.col-1] == 'O') {
                board[current.row][current.col-1] = 'P';
                list.add(new Pos(current.row,current.col-1));
            }
            if(current.col < board[0].length-1 && board[current.row][current.col+1] == 'O') {
                board[current.row][current.col+1] = 'P';
                list.add(new Pos(current.row,current.col+1));
            }
        }
        
        for(int i=0; i<board.length; i++) {
            for(int j=0; j<board[0].length; j++) {
                if(board[i][j] == 'P')
                    board[i][j] = 'O';
                else if(board[i][j] == 'O')
                    board[i][j] = 'X';
            }
        }
    }
    
    class Pos {
        int row;
        int col;
        public Pos(int row, int col) {
            this.row = row;
            this.col = col;
        }
    }

 

posted on 2015-03-23 18:03  linxiong1991  阅读(78)  评论(0编辑  收藏  举报

导航