当前位置: 首页 > 图灵资讯 > 技术篇> #yyds干货盘点# LeetCode程序员面试金典:被围绕的区域

#yyds干货盘点# LeetCode程序员面试金典:被围绕的区域

来源:图灵教育
时间:2023-06-14 09:49:01

题目:

给你一个 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如果两个元素在水平或垂直方向相邻,则称为“连接”。

示例 2:

输入:board = [["X"]]

输出:[[[”X"]]

代码实现:

class Solution {    int n, m;    public void solve(char[][] board) {        n = board.length;        if (n == 0) {            return;        }        m = board[0].length;        for (int i = 0; i < n; i++) {            dfs(board, i, 0);            dfs(board, i, m - 1);        }        for (int i = 1; i < m - 1; i++) {            dfs(board, 0, i);            dfs(board, n - 1, i);        }        for (int i = 0; i < n; i++) {            for (int j = 0; j < m; j++) {                if (board[i][j] == 'A') {                    board[i][j] = 'O';                } else if (board[i][j] == 'O') {                    board[i][j] = 'X';                }            }        }    }    public void dfs(char[][] board, int x, int y) {        if (x < 0 || x >= n || y < 0 || y >= m || 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);    }}