【题目描述】
给你一个 m x n
的矩阵 board
,由若干字符 'X'
和 'O'
,找到所有被 'X'
围绕的区域,并将这些区域里所有的 'O'
用 'X'
填充。
https://leetcode.cn/problems/surrounded-regions/description/
【示例】
【代码】leecode
package com.company;
import java.util.*;
// 2023-04-26
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++){
// 这里判断的是边缘的部分
boolean isEdge = i == 0 || j == 0 || i == m - 1 || j == n - 1;
// 边缘存在 0
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] == '#' || board[i][j] == 'X') return;
// 说明已经搜索过了
// 遍历后, 所有非边缘的 0 都变成了 #
board[i][j] = '#';
// 上 下 左 右
dfs(board, i - 1, j);
dfs(board, i + 1, j);
dfs(board, i, j - 1);
dfs(board, i, j + 1);
}
}
public class Test {
public static void main(String[] args) {
// 输出:[["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
new Solution().solve(new char[][] {{'X','X','X','X'},{'X','O','O','X'},{'X','X','O','X'},{'X','O','X','X'}});
new Solution().solve(new char[][] {{'X'}}); // 输出:['X']
}
}