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

[解题思路]

 board的四个边上的O是无法被X包围的,故如果在四个边上发现O,则这些O应当被保留 从这些O出发继续寻找相邻的O,这些O也是要保留的

 等这些O都标记结束,则剩余的O就应该被改成X

 

public class Solution {
    public void solve(char[][] board) {
      
        if(board == null||board.length == 0||board[0] == null||board[0].length == 0)
            return;
        int y = board.length;
        int x = board[0].length;
        LinkedList<location> mylist = new LinkedList<location>();
        for(int i = 0; i < x; i++)
        {
            // 第一行
            if(board[0][i] == 'O')
            {
                board[0][i] = 'Y';
                mylist.add(new location(0, i));
            }
            // 最后一行
            if(board[y-1][i] == 'O')
            {
                board[y-1][i] = 'Y';
                mylist.add(new location(y-1, i));
            }
        }
        for(int i = 0; i < y; i++)
        {   
            // 第一列
            if(board[i][0] == 'O')
            {
                board[i][0] = 'Y';
                mylist.add(new location(i, 0));
            }
            //最后一列
            if(board[i][x-1] == 'O')
            {
                board[i][x-1] = 'Y';
                mylist.add(new location(i, x-1));
            }
        }
        while(!mylist.isEmpty())
        {
            location myloc = mylist.poll();
            if(myloc.x - 1 >= 0 && board[myloc.x - 1][myloc.y] == 'O')
            {
                board[myloc.x - 1][myloc.y] = 'Y';
                mylist.add(new location(myloc.x - 1, myloc.y));
            }
            if(myloc.y - 1 >= 0 && board[myloc.x][myloc.y - 1] == 'O')
            {
                board[myloc.x][myloc.y - 1] = 'Y';
                mylist.add(new location(myloc.x, myloc.y - 1));
            }
            if(myloc.x + 1 < y && board[myloc.x + 1][myloc.y] == 'O')
            {
                board[myloc.x + 1][myloc.y] = 'Y';
                mylist.add(new location(myloc.x + 1, myloc.y));
            }
            if(myloc.y + 1 < x && board[myloc.x][myloc.y + 1] == 'O')
            {
                board[myloc.x][myloc.y + 1] = 'Y';
                mylist.add(new location(myloc.x, myloc.y + 1));
            }
        }
        
        for(int i = 0; i < y; i++){
            for(int j = 0; j < x; j++)
            {
                if(board[i][j] == 'Y')
                    board[i][j] = 'O';
                else if(board[i][j] == 'O')
                    board[i][j] = 'X';
            }    
        }
    }
    class location{
        int x;
        int y;
        location(int x, int y)
        {this.x = x; this.y = y;}
    }
}

 

 

 

 

posted @ 2014-02-04 14:23  Razer.Lu  阅读(219)  评论(0编辑  收藏  举报