130. Surrounded Regions

Posted apanda009

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了130. Surrounded Regions相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

130. Surrounded Regions

130. Surrounded Regions

130. Surrounded Regions

130. Surrounded Regions

130. Surrounded Regions

130. Surrounded Regions