leetcode130.被围绕的区域-创新互联-成都快上网建站

leetcode130.被围绕的区域-创新互联

题目描述:

给你一个m x n的矩阵board,由若干字符'X''O',找到所有被'X'围绕的区域,并将这些区域里所有的 'O''X'填充。

创新互联科技有限公司专业互联网基础服务商,为您提供乐山服务器托管高防服务器租用,成都IDC机房托管,成都主机托管等互联网服务。样例:

示例 1:

输入:board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
输出:[["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
解释:被围绕的区间不会存在于边界上,换句话说,任何边界上的 'O'都不会被填充为 'X'。 任何不在边界上,或不与边界上的 'O'相连的 'O'最终都会被填充为 'X'。如果两个元素在水平或垂直方向相邻,则称它们是“相连”的。

示例 2:

输入:board = [["X"]]
输出:[["X"]]
提示:
  • m == board.length
  • n == board[i].length
  • 1<= m, n<= 200
  • board[i][j]'X''O'
Java程序:
class Solution {
    public void solve(char[][] board) {
        if (board == null || board.length == 0) return;
        int m = board.length;
        int n = board[0].length;
        for (int i = 0; i< m; i++) {
            for (int j = 0; j< n; j++) {
                // 从边缘o开始搜索
                boolean isEdge = i == 0 || j == 0 || i == m - 1 || j == n - 1;
                if (isEdge && board[i][j] == 'O') {
                    dfs(board, i, j);
                }
            }
        }

        for (int i = 0; i< m; i++) {
            for (int j = 0; j< n; j++) {
                if (board[i][j] == 'O') {
                    board[i][j] = 'X';
                }
                if (board[i][j] == '#') {
                    board[i][j] = 'O';
                }
            }
        }
    }

    public void dfs(char[][] board, int i, int j) {
        if (i< 0 || j< 0 || i >= board.length  || j >= board[0].length || board[i][j] == 'X' || board[i][j] == '#') {
            // board[i][j] == '#' 说明已经搜索过了. 
            return;
        }
        board[i][j] = '#';
        dfs(board, i - 1, j); // 上
        dfs(board, i + 1, j); // 下
        dfs(board, i, j - 1); // 左
        dfs(board, i, j + 1); // 右
    }
}

你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧


分享名称:leetcode130.被围绕的区域-创新互联
文章位置:http://kswjz.com/article/dpgoco.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流