【LeetCode】Surrounded Regions

133 篇文章 0 订阅
121 篇文章 2 订阅
Surrounded Regions 
Total Accepted: 4485 Total Submissions: 31870 My Submissions
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
Discuss
        个人感觉这个题目和九度 题目1460:Oil Deposit很像,解题思路参考( Jobdu 题目1460:Oil Deposit),各位不妨思考一下相似之处。
        好吧,我承认第一遍看这个题目有点不太懂。
        其实题目大意是这样的,从一个二维矩阵中寻找所有被X包围的O,如果找到的话,将所有的O替换为X。
        BFS,基本思路是从边界开始找起,同时标记是否访问过,防止重复搜索。如果边界有O的话,从该点开始宽度优先搜索,搜索到O就标记访问过。针对每个边界上为O的点搜索,这样就可以搜索到结果。搜索完毕之后,所有的为O的未访问过的点,都为被X包围的点,直接赋值为X即可。

Java AC

public class Solution {
    public int stepArr[][] = {{-1,0},{1,0},{0,-1},{0,1}};
    public int visit[][];
    public int m, n;
    public void solve(char[][] board) {
        if(board == null || board.length == 0){
            return;
        }
        m = board.length;
        n = board[0].length;
        visit = new int[m][n];
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if((i == 0 || i == m-1 || j == 0 || j == n-1) 
                            && visit[i][j] == 0 && board[i][j] == 'O'){
                    bfs(i,j,board);
                }
            }
        }
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(visit[i][j] != 1 && board[i][j] == 'O'){
                    board[i][j] = 'X';
                }
            }
        }
    }
    public void bfs(int nodei, int nodej, char board[][]){
        Queue<Node> queue = new LinkedList<Node>();
        Node node = new Node(nodei, nodej);
        queue.offer(node);
        visit[nodei][nodej] = 1;
        while(!queue.isEmpty()){
            node = queue.peek();
            queue.poll();
            int newx = 0;
            int newy = 0;
            for(int i = 0; i < 4; i++){
                newx = node.x + stepArr[i][0];
                newy = node.y + stepArr[i][1];
                if(newx >= 0 && newx < m && newy >= 0 && newy < n 
                            && visit[newx][newy] == 0 && board[newx][newy] == 'O'){
                    visit[newx][newy] = 1;
                    queue.offer(new Node(newx, newy));
                }
            }
        }
    }
    public class Node{
        int x;
        int y;
        Node(int x, int y){
            this.x = x;
            this.y = y;
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值