玩命加载中 . . .

130-被围绕的区域


LeetCode 130. 被围绕的区域

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

示例 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'。如果两个元素在水平或垂直方向相邻,则称它们是“相连”的。

method

先把边缘的联通O区域都变成A,后面再遍历的时候,矩阵中的O就都是被围绕的区域,直接改成X,同时也把A还原回O

int m, n;
void dfs(vector<vector<char>>& board, int x, int y) {
    if (x < 0 || x >= m || y < 0 || y >= n || board[x][y] != 'O') return;
    board[x][y] = 'A';
    dfs(board, x - 1, y);
    dfs(board, x + 1, y);
    dfs(board, x, y + 1);
    dfs(board, x, y - 1);
}
void solve(vector<vector<char>>& board) {
    m = board.size(), n = board[0].size();
    for (int i = 0; i < m; i++) {
        dfs(board, i, 0);
        dfs(board, i, n - 1);
    }
    for (int j = 0; j < n; j++) {
        dfs(board, 0, j);
        dfs(board, m - 1, j);
    }
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (board[i][j] == 'A') board[i][j] = 'O';
            else if (board[i][j] == 'O') board[i][j] = 'X';
        }
    }
}

文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录