程序员社区

LeetCode-130-被围绕的区域

LeetCode-130-被围绕的区域

130. 被围绕的区域

难度中等

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

示例 1:

LeetCode-130-被围绕的区域插图
img
输入: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'

思路:

从边界出发吧,先把边界上和 O 连通点找到, 把这些变成 B,然后遍历整个 boardO 变成 X, 把 B 变成 O

如下图所示:

LeetCode-130-被围绕的区域插图1
image-20210613111722202
class Solution {
    // 从边界开始感染的方法
    public static void solve(char[][] board) {
        if (board == null || board.length == 0 || board[0] == null || board[0].length == 0) {
            return;
        }
        int N = board.length;
        int M = board[0].length;
        for (int j = 0; j < M; j++) {
            if (board[0][j] == 'O') {
                free(board, 0, j);
            }
            if (board[N - 1][j] == 'O') {
                free(board, N - 1, j);
            }
        }
        for (int i = 1; i < N - 1; i++) {
            if (board[i][0] == 'O') {
                free(board, i, 0);
            }
            if (board[i][M - 1] == 'O') {
                free(board, i, M - 1);
            }
        }
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                if (board[i][j] == 'O') {
                    board[i][j] = 'X';
                }
                if (board[i][j] == 'F') {
                    board[i][j] = 'O';
                }
            }
        }
    }

    public static void free(char[][] board, int i, int j) {
        if (i < 0 || i == board.length || j < 0 || j == board[0].length || board[i][j] != 'O') {
            return;
        }
        board[i][j] = 'F';
        free(board, i + 1, j);
        free(board, i - 1, j);
        free(board, i, j + 1);
        free(board, i, j - 1);
    }
}
LeetCode-130-被围绕的区域插图2
image-20210613111851795
赞(0) 打赏
未经允许不得转载:IDEA激活码 » LeetCode-130-被围绕的区域

一个分享Java & Python知识的社区