zoukankan      html  css  js  c++  java
  • 130. Surrounded Regions(js)

    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.

    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
    

    Explanation:

    Surrounded regions shouldn’t be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically.

    题意:给定一个带有‘x’和‘o’的二维数组,求所有被x包围的o都同化成x,返回这个二维数组。

    代码如下:

    /**
     * @param {character[][]} board
     * @return {void} Do not return anything, modify board in-place instead.
     */
    var solve = function(board) {
        for(let i=0;i<board.length;i++){
            for(let j=0;j<board[i].length;j++){
    //             如果o处于边界上
                if((i===0 || i===board.length-1 || j===0 || j===board[i].length-1) && board[i][j]==='O'){
                    dfs(board,i,j);
                }
            }
        }
        for(let i=0;i<board.length;i++){
            for(let j=0;j<board[i].length;j++){
    //             将不处于边界上的o,或者不与边界上相邻的o转化成x
                if(board[i][j]==='O') board[i][j]='X';
                if(board[i][j]==='$') board[i][j]='O';
            }
        }
    };
    var dfs=function(board,i,j){
    //     将与处于边界的o变成$
        if(board[i][j]==='O'){
            board[i][j]='$';
            if(i>0 && board[i-1][j]==='O'){
                dfs(board,i-1,j);
            }
            if(i<board.length-1 && board[i+1][j]==='O'){
                dfs(board,i+1,j);
            }
            if(j>0 && board[i][j-1]==='O'){
                dfs(board,i,j-1);
            }
            if(j<board[i].length-1 && board[i][j+1]){
                dfs(board,i,j+1);
            }
        }
    }
  • 相关阅读:
    测试
    【八十一题题目合集 微软面试100题 第八十一题】
    排队问题 【微软面试100题 第八十题】
    fiddler 正则 重定向IP
    浮动div 内部元素 垂直居中
    css 诡异的多出来的几像素
    前端开发 注意问题(1)input type=“number”
    实时监听input输入
    sudo执行命令时环境变量被重置的解决方法
    laravel4 中 Redirect::intended和Redirect::guest的关系及用法
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/10923805.html
Copyright © 2011-2022 走看看