Surrounded Regions @LeetCode

几个月不做 再看仍然是相当麻烦的一道jghh
摘要由CSDN通过智能技术生成

几个月不做 再看仍然是相当麻烦的一道题目啊

查了一下资料,使用DFS时 在大数据集合时会栈溢出,所以我们用队列来进行BFS.

只需要扫描边界,与边界连通的全部置为B, 再扫一次 原来的O置为x, B置为O,完工。

使用队列 BFS时,存入队列的元素,代表下一次准备要扫描其4个邻接点。(啊啊啊,这个逻辑超难想的,因为入队代表的是下一个要搜索它的周边,而不是要搜索它本身)

http://www.cnblogs.com/feiling/p/3304120.html


public class Solution {
    public void solve(char[][] board) {
        if (board == null) {
            return;
        }
        
        if (board.length == 0) {
            return;
        }
        
        int row = board.length;
        int col = board[0].length;
        
        // BFS the first line and the last line.
        for (int i = 0; i < col; i++) {
            bfs(board, 0, i);
            bfs(board, row - 1, i);
        }
        
        // BFS the left line and the right line.
        for (int i = 1; i < row - 1; i++) {
            bfs(board, i, 0);
            bfs(board, i, col - 1);
        }
        
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (board[i][j] == 'B') {
                    board[i][j] = 'O';
                } else if (board[i][j] == 'O') {
                    board[i][j] = 'X';
                }
            }
        }
        
        return;
    }
    
    public void bfs(char[][] board, int x, int y) {
        Queue
   
   
    
     q = new LinkedList
    
    
     
     ();
        
        // 把x, y放入queue代表准备要访问它的邻接点
        visit(board, x, y, q);
        while (!q.isEmpty()) {
            int num = q.poll();
            int r = num / board[0].length;
            int c = num % board[0].length;
            
            // visit the surrounded points.
            visit(board, r + 1, c, q);
            visit(board, r - 1, c, q);
            visit(board, r, c + 1, q);
            visit(board, r, c - 1, q);
        }
        
        return;
    }
    
    public void visit(char[][] board, int x, int y, Queue
     
     
      
       q) {
        int row = board.length;
        int col = board[0].length;
        if (x < 0 || x >= row || y < 0 || y >= col) {
            return;
        }
        
        if (board[x][y] != 'O') {
            return;
        }
        
        board[x][y] = 'B';
        
        q.offer(col * x + y);
        
        return;
    }
}

     
     
    
    
   
   







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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值