zoukankan      html  css  js  c++  java
  • 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 '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存入queue BFS
    public class Solution {
        //BFS
        public void solve(char[][] board) {
            if(board.length == 0 || board[0].length == 0)
                return;
            Queue<int[]> queue = new LinkedList<>();
            int rowEdge = 0;
            int colEdge = 0;
            for(int i = 0; i < board.length; i++){
                for(int j = 0 ; j < board[0].length; j++){
                    if((i == 0 || i == board.length -1 || j == 0 || j == board[0].length-1) && board[i][j] == 'O'){
                        board[i][j] = '*';
                        queue.add(new int[]{i,j});
                    }
                }
            }
            while(!queue.isEmpty()){
                int gate[] = queue.poll();
                int row = gate[0];
                int col = gate[1];
                if(row > 0 && board[row -1][col] == 'O'){
                    board[row-1][col] = '*';
                    queue.add(new int[]{row-1, col});
                }
                if(col > 0 && board[row][col-1] == 'O'){
                    board[row][col-1] = '*';
                    queue.add(new int[]{row, col-1});
                }
                if(row < board.length -1 && board[row +1][col] == 'O'){
                    board[row+1][col] = '*';
                    queue.add(new int[]{row+1, col});
                }
                if(col < board[0].length -1 && board[row][col + 1] == 'O'){
                    board[row][col+1] = '*';
                    queue.add(new int[]{row, col+1});
                }
            }
            for(int i = 0; i < board.length; i++){
                for(int j = 0 ; j < board[0].length; j++){
                    if(board[i][j] == 'O'){
                        board[i][j] = 'X';
                    }
                    if(board[i][j] == '*'){
                        board[i][j] = 'O';
                    }
                }
            }
        }
    }
  • 相关阅读:
    java数的相加
    读大道至简第二章有感
    读大道至简第一章有感
    课题的跨专业组队
    返回一个整数数组中最大子数组的和。
    《构建之法》阅读笔记02
    单元测试(2)
    软件工程个人作业03
    单元测试
    团队
  • 原文地址:https://www.cnblogs.com/joannacode/p/5947922.html
Copyright © 2011-2022 走看看