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);
            }
        }
    }
  • 相关阅读:
    PHP变量及其操作
    PHP基本语法
    PHP安装与配置
    MySQL安装与配置
    获取一个目录的父目录
    Image控件播放 GIF文件
    保存网页MHT
    注册全局热键
    使用多线程实现打字效果
    Delphi 调用外部程序并等待其运行结束
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/10923805.html
Copyright © 2011-2022 走看看