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);
            }
        }
    }
  • 相关阅读:
    R语言高级编程系列之面向对象的类型系统--S3对象
    数据挖掘之KNN算法(C#实现)
    数据挖掘之决策树ID3算法(C#实现)
    C#矩阵运算类库
    2020年图机器学习的最新趋势
    ios开发笔记-7-bug解决
    ios开发笔记-6-ReactiveCocoa
    ios开发笔记-5-配置文件
    ios开发笔记-4-app打包测试流程
    ios开发笔记-3-微信支付
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/10923805.html
Copyright © 2011-2022 走看看