1. 程式人生 > >130. Surrounded Regions

130. Surrounded Regions

ons void while boa apt pty 改變 int style

Given a 2D board containing X and O (the letter O), capture all regions surrounded by X.

A region is captured by flipping all Os into Xs in that surrounded region.

For example,
X X X X
X O O X
X X O X
X O X X
After running your function, the board should be:

X X X X
X X X X
X X X X
X O X X

矩陣的bfs, 套路一致,從外向內, 很easy

構造類, 遍歷矩陣建立圖

bfs要點在於如何建圖, 是否建類, 建比較器, 建方向容器, 建走過的路的存儲器(數組, 或者set, list) 如何遍歷(堆不空?), 遍歷到內部的點時判斷是否符合題意(邊界, 走過), 再考慮題意, 判斷當前的點是否符合題意來加入結果的容器 或結果值, 將當前的點加入堆中是否要改變值啊什麽的, 關鍵在於建立的是什麽圖. 裏面的點是怎麽個意思, 都是題意的轉化

class Cell {
    int x, y;
    public Cell(int x, int y) {
        this.x = x;
        this.y = y;
    }
}
public class Solution {
   
    public void solve(char[][] board) {
        if(board == null || board.length == 0 || board[0].length == 0) return;
        int m = board.length;
        int n = board[0].length;
        Queue<Cell> q = new LinkedList<>();
        int[][] directions = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        boolean [][] visited = new boolean[m][n];
        for (int j=0; j<board[0].length; j++) {
            if (board[0][j] == ‘O‘) q.offer(new Cell(0, j));
            if (board[board.length-1][j] == ‘O‘) q.offer(new Cell(board.length-1, j));
            visited[0][j] = true;
            visited[m - 1][j] =  true;
        }
        for (int i=0; i<board.length; i++) {
            if (board[i][0] == ‘O‘) q.offer(new Cell(i, 0));
            if (board[i][board[0].length-1] == ‘O‘) q.offer(new Cell(i, board[0].length-1));
            visited[i][0] = true;
            visited[i][n - 1] =  true;
        }
        while (!q.isEmpty()) {
            Cell cur = q.poll();
            board[cur.x][cur.y] = ‘$‘;
            
            for (int[] dir : directions) {
                int x = dir[0] + cur.x;
                int y = dir[1] + cur.y;
                if (x < 0 || y < 0 || x >= m || y >= n || visited[x][y] || board[x][y] == ‘X‘) {
                    continue;
                }
                visited[x][y] = true;
                q.offer(new Cell(x, y));
            }
        }
        for (int i=0; i<board.length; i++) {
            for (int j=0; j<board[0].length; j++) {
                if (board[i][j] == ‘X‘) continue;
                else if (board[i][j] == ‘$‘) board[i][j] = ‘O‘;
                else if (board[i][j] == ‘O‘) board[i][j] = ‘X‘;
            }
        }
    }
}

  

130. Surrounded Regions