【BFS】LeetCode 130. 被围绕的区域

题目链接

130. 被围绕的区域

思路

BFS 模板的简单变换。

分析题目可以知道,如果一片 O 想要存活,则这一片 O 必然与边界接触。我们可以遍历四个边界,找到所有与边界接触的 O,则剩下的就是需要变为 XO

代码

class Solution {
    void bfs(int i, int j, char[][] board, boolean[][] visited, boolean[][] changed){
        int[] dx = new int[]{1, 0, -1, 0};
        int[] dy = new int[]{0, 1, 0, -1};
        Queue<Pair<Integer, Integer>> queue = new LinkedList<>();

        queue.offer(new Pair<>(i, j));
        visited[i][j] = true;
        changed[i][j] = false;
        while(!queue.isEmpty()){
            Pair<Integer, Integer> pair = queue.remove();
            for(int k = 0; k < 4; k++){
                int nextX = pair.getKey() + dx[k];
                int nextY = pair.getValue() + dy[k];
                if(0 <= nextX && nextX < board.length && 0 <= nextY && nextY < board[0].length
                    && board[nextX][nextY] == 'O' && !visited[nextX][nextY]){
                    queue.offer(new Pair<>(nextX, nextY));
                    visited[nextX][nextY] = true;
                    changed[nextX][nextY] = false;
                }
            }
        }
    }

    public void solve(char[][] board) {
        boolean[][] visited = new boolean[board.length][board[0].length];
        // sign a element whether to be changed
        boolean[][] changed = new boolean[board.length][board[0].length];
        for(int i = 0; i < changed.length; i++){
            Arrays.fill(changed[i], true);
        }

        for(int i = 0; i < board[0].length; i++){
            if(board[0][i] == 'O'){
                bfs(0, i, board, visited, changed);
            }
            if(board[board.length - 1][i] == 'O'){
                bfs(board.length - 1, i, board, visited, changed);
            }
        }

        for(int i = 0; i < board.length; i++){
            if(board[i][0] == 'O'){
                bfs(i, 0, board, visited, changed);
            }
            if(board[i][board[0].length - 1] == 'O'){
                bfs(i, board[0].length - 1, board, visited, changed);
            }
        }

        for(int i = 0; i < board.length; i++){
            for(int j = 0; j < board[0].length; j++){
                if(changed[i][j]){
                    board[i][j] = 'X';
                }
            }
        }
    }
}
posted @ 2023-01-13 15:06  Frodo1124  阅读(28)  评论(0编辑  收藏  举报