leetcode-- 130. Surrounded Regions

参考:http://blog.csdn.net/worldwindjp/article/details/19251995
Given a 2D board containing ‘X’ and ‘O’ (the letter 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

**主要学到:
四个方向遍历时候的简洁代码,bfs学习。**

AC代码:

public class Solution {
    public void solve(char[][] board) {
        if(board == null || board.length<=0){
            return ;
        }
        int lenX = board.length;
        int lenY = board[0].length;
        Deque<Integer> queue = new ArrayDeque<>();
        for(int i=0; i<lenX; i++){
            for(int j=0; j<lenY; j++){
                if(i==0||j==0||i==lenX-1 || j==lenY-1){
                    if(board[i][j]=='O'){
                        queue.offer(i*lenY+j);
                    }
                }
            }
        }
        //四个方向的数组表示
        int[][] dir = {{-1,0},{1,0},{0,-1},{0,1}};
        //标识阶段,将不能被包围的全部标识一遍
        while(queue.size()>0){
            int pos = queue.poll();
            int posX = pos/lenY;
            int posY = pos%lenY;
            if(board[posX][posY]=='Y'){
                continue;
            }
            board[posX][posY] = 'Y';
            //向四个方向扩展
            for(int k=0; k<4; k++){
                int x = posX + dir[k][0];
                int y = posY + dir[k][1];
                if(x<lenX && x>=0 && y>=0 && y<lenY && board[x][y]=='O'){
                    queue.offer(x*lenY+y);
                }
            }
        }
        for(int i=0; i<lenX; i++){
            for(int j=0; j<lenY; j++){
                if(board[i][j]=='Y'){
                    board[i][j]='O';
                }else if(board[i][j]=='O'){
                    board[i][j]='X';
                }
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值