//给定一个二维的矩阵,包含 'X' 和 'O'(字母 O)。 // // 找到所有被 'X' 围绕的区域,并将这些区域里所有的 'O' 用 'X' 填充。 // // 示例: // // 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'。如果两个元素在水平或垂直方向相邻,则称它们是“相连”的。 // Related Topics 深度优先搜索 广度优先搜索 并查集 // 👍 468 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { public void solve(char[][] board) { int m = board.length - 1; int n = board[0].length - 1; for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (board[i][j] == 'O'){ if (solveRun(board, i, j, m, n)) { board[i][j] = 'X'; } } } } } public boolean solveRun(char[][] board, int i, int j, int m, int n) { if (i > m || i < 0 || j > n || j < 0) return false; if (board[i][j] == 'X') return true; boolean left = solveLeft(board,i, j - 1, m, n); boolean down = solveDown(board,i + 1, j, m, n); boolean right = solveRight(board,i, j + 1, m, n); boolean up = solveUp(board,i - 1, j, m, n); return left && right && down && up; } public boolean solveLeft(char[][] board, int i, int j, int m, int n) { if (i > m || i < 0 || j > n || j < 0) return false; if (board[i][j] == 'X') return true; return solveLeft(board,i, j - 1, m, n); } public boolean solveDown(char[][] board, int i, int j, int m, int n) { if (i > m || i < 0 || j > n || j < 0) return false; if (board[i][j] == 'X') return true; return solveDown(board,i + 1, j, m, n); } public boolean solveRight(char[][] board, int i, int j, int m, int n) { if (i > m || i < 0 || j > n || j < 0) return false; if (board[i][j] == 'X') return true; return solveRight(board,i, j + 1, m, n); } public boolean solveUp(char[][] board, int i, int j, int m, int n) { if (i > m || i < 0 || j > n || j < 0) return false; if (board[i][j] == 'X') return true; return solveUp(board,i - 1, j, m, n); } } //leetcode submit region end(Prohibit modification and deletion)
2021-02-07 被包围的矩阵
最新推荐文章于 2024-04-20 16:21:06 发布