Surrounded Regions

来源:互联网 发布:韩略村伏击战知乎 编辑:程序博客网 时间:2024/05/20 20:03

1 题目描述

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

2 题目解答

解题思路:

首先可以确定的是边缘的'O' 永远都不会被包围,所以只要按着边缘的'O' 找,找出它周围身边的'O' ,所以可以用BFS或者DFS来遍历

代码实现

public class Solution{    //访问边缘的节点    public void solve(char[][] board) {        if(board.length == 0 || board[0].length == 0)            return ;        int row = board.length;        int col = board[0].length;        for(int i = 0; i < row; i++){            toBFS(board, i, 0);            toBFS(board, i, col-1);        }        for(int j = 0; j < col; j++){            toBFS(board, 0, j);            toBFS(board, row-1, j);        }        for(int i = 0; i < row; i++){            for(int j = 0; j < col; j++){                if(board[i][j] == 'O')                    board[i][j] = 'X';                if(board[i][j] == '#')                    board[i][j] = 'O';            }        }    }    /**     * 函数功能:广度优先遍历 把等于 O 的字符替换成 #     * 队列里面保存的是二维数组的 i 和 j     *     */    public void toBFS(char[][] board, int i, int j){        if(board[i][j] != 'O')            return ;        int row = board.length;        int col = board[0].length;        ArrayDeque<Holder> deque = new ArrayDeque<>();        //队列里面保存的是二位数组的i, j        deque.addLast(new Holder(i, j));        while(deque.size() != 0){            Holder holder = deque.pollFirst();            int first = holder.i;            int second = holder.j;            if(first < 0 || first >= row || second < 0 || second >= col)                continue;            if(board[first][second] != 'O')                continue;            board[first][second] = '#';            deque.addLast(new Holder(first-1, second));            deque.addLast(new Holder(first+1, second));            deque.addLast(new Holder(first, second-1));            deque.addLast(new Holder(first, second+1));        }    }    /**     * 函数功能:深度优先遍历  把等于 O 的字符替换成 #     * 当数据量大的时候会发生栈溢出     */    public void toDFS(char[][] board, int i, int j) {        int row = board.length;        int col = board[0].length;        if (i < 0 || i >= row || j < 0 || j >= col)            return;        if (board[i][j] != 'O')            return;        board[i][j] = '#';        toDFS(board, i - 1, j);        toDFS(board, i + 1, j);        toDFS(board, i, j - 1);        toDFS(board, i, j + 1);    }    public static class Holder {        public int i;        public int j;        public Holder(int i, int j){            this.i = i;            this.j = j;        }    }}
0 0
原创粉丝点击