LeetCode刷題記112-130. 被圍繞的區域

鹹蛋黃麥芽糖小餅乾發表於2020-12-06

LeetCode刷題記112

130. 被圍繞的區域

題目
在這裡插入圖片描述

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

4/5
112/150

相關文章