LeetCode每日一题:包围的XO

问题描述

Given a 2D board containing'X'and'O', capture all regions surrounded by'X'.
A region is captured by flipping all'O's into'X's 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

问题分析

这道题要我们做的是寻找’O’,当‘O’被‘X’包围时,将‘O’变成’X’,当‘O’在边界上时,它本身与和它上下左右相连的‘O’不用变化
这道题可以采用广度优先遍历BFS,只要寻找到边界上的‘O’,然后广度遍历它的周围上下左右四个角是否有‘O’,把这些标记过得‘O’不变,把没有标记过得‘O’变成’X’

代码实现

public void solve(char[][] board) {
        if (board.length == 0) return;
        int len = board[0].length;
        boolean[][] visited = new boolean[board.length][len];
        LinkedList queue = new LinkedList<>();//用队列存储坐标
        int[][] direction = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};//定义四个方向
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (board[i][j] == 'O' && visited[i][j] == false) {
                    boolean surrounded = true;
                    ArrayList visitedPoint = new ArrayList<>();//存储已经访问过的点
                    queue.offer(i * board[0].length + j);
                    visited[i][j] = true;
                    while (queue.isEmpty() == false) {//BFS搜索
                        int point = queue.poll();
                        visitedPoint.add(point);
                        int x = point / len;//相除和取模拿到x,y坐标
                        int y = point % len;
                        for (int k = 0; k < 4; k++) {//分别向四个方向进行搜索
                            int nextX = x + direction[k][0];
                            int nextY = y + direction[k][1];
                            if (nextX >= 0 && nextX < board.length && nextY >= 0 && nextY < len) {
                                if (board[nextX][nextY] == 'O' && visited[nextX][nextY] == false) {
                                    queue.offer(nextX * len + nextY);
                                    visited[nextX][nextY] = true;
                                }
                            } else {
                                surrounded = false;//边缘点不用考虑
                            }
                        }
                    }
                    if (surrounded) {
                        for (int p:visitedPoint){
                            board[p/len][p%len]='X';
                        }
                    }
                }
            }
        }
    }

你可能感兴趣的:(LeetCode每日一题:包围的XO)