我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/surrounded-regions/description/

题目描述:

LeetCode130——被围绕的区域

知识点:深度优先遍历

思路:对边界上的'O'进行深度优先遍历标记遍历到的'O',将未遍历到的'O'填充为'X'

时间复杂度和空间复杂度均是O(n),其中n为区域中的点数。

JAVA代码:

public class Solution {
    int[][] directions = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

    public void solve(char[][] board) {
        if(board.length == 0) {
            return;
        }
        boolean[][] visited = new boolean[board.length][board[0].length];
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if(i == 0 || i == board.length - 1 || j == 0 || j == board[0].length - 1) {
                    if(board[i][j] == 'O' && !visited[i][j]) {
                        dfs(board, i, j, visited);
                    }
                }
            }
        }
        for (int i = 1; i < board.length; i++) {
            for (int j = 1; j < board[0].length; j++) {
                if(!visited[i][j] && board[i][j] == 'O') {
                    board[i][j] = 'X';
                }
            }
        }
    }

    private void dfs(char[][] board, int i, int j, boolean[][] visited) {
        visited[i][j] = true;
        for(int k = 0; k < 4; k++) {
            int newi = i + directions[k][0];
            int newj = j + directions[k][1];
            if(isValid(board, newi, newj) && !visited[newi][newj] && board[newi][newj] == 'O') {
                dfs(board, newi, newj, visited);
            }
        }
    }

    private boolean isValid(char[][] board, int i, int j) {
        return i >= 0 && i < board.length && j >= 0 && j < board[0].length;
    }
}

LeetCode解题报告:

LeetCode130——被围绕的区域

 

相关文章:

  • 2021-11-01
  • 2021-06-11
  • 2021-08-27
  • 2021-09-21
  • 2022-12-23
  • 2021-11-11
  • 2021-08-06
  • 2022-12-23
猜你喜欢
  • 2021-07-19
  • 2021-10-30
  • 2021-06-05
  • 2021-11-02
  • 2022-02-20
  • 2021-06-23
  • 2022-01-25
相关资源
相似解决方案