477.Surrounded Regions-被围绕的区域(中等题)

本文介绍了一种解决二维矩阵中被‘X’围绕的‘O’区域问题的算法。通过使用队列进行广度优先搜索,从边界上的‘O’开始遍历,将可达的‘O’标记为临时状态,最后将未被标记的‘O’转换为‘X’,实现了矩阵的有效修改。

被围绕的区域

  1. 题目

    给一个二维的矩阵,包含 ‘X’ 和 ‘O’, 找到所有被 ‘X’ 围绕的区域,并用 ‘X’ 填充满。

  2. 样例

    给出二维矩阵:
    这里写图片描述
    把被 ‘X’ 围绕的区域填充之后变为:
    这里写图片描述

  3. 题解

public class Solution {
    private static Queue<Integer> queue = null;
    private static char[][] board;
    private static int rows = 0;
    private static int cols = 0;
    /**
     * @param board a 2D board containing 'X' and 'O'
     * @return void
     */
    public void surroundedRegions(char[][] board) {
        if (board.length == 0 || board[0].length == 0) 
        {
            return;
        }
        queue = new LinkedList<Integer>();
        this.board = board;
        rows = board.length;
        cols = board[0].length;

        for (int i = 0; i < rows; i++) 
        {
            enqueue(i, 0);
            enqueue(i, cols - 1);
        }

        for (int j = 1; j < cols - 1; j++) 
        {
            enqueue(0, j);
            enqueue(rows - 1, j);
        }

        while (!queue.isEmpty()) 
        {
            int cur = queue.poll();
            int x = cur / cols;
            int y = cur % cols;

            if (board[x][y] == 'O') 
            {
                board[x][y] = 'D';
            }

            enqueue(x - 1, y);
            enqueue(x + 1, y);
            enqueue(x, y - 1);
            enqueue(x, y + 1);
        }

        for (int i = 0; i < rows; i++) 
        {
            for (int j = 0; j < cols; j++) 
            {
                if (board[i][j] == 'D') 
                {
                    board[i][j] = 'O';
                }
                else if (board[i][j] == 'O') 
                {
                    board[i][j] = 'X';
                }
            }
        }

        queue = null;
        this.board = null;
        rows = 0;
        cols = 0;
    }

    public static void enqueue(int x, int y) 
    {
        if (x >= 0 && x < rows && y >= 0 && y < cols && board[x][y] == 'O')
        {  
            queue.offer(x * cols + y);
        }
    }
}

Last Update 2016.11.19

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值