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);
            }
        }
    }
  • 相关阅读:
    开通博客第一天
    Vue 打包配置productionSourceMap 的记录
    supervisorctl 的 简单记录
    mvn打包方式记录
    springboot日志配置,关于logback
    springboot集成swagger
    关于mapper文件的bean
    elasticsearch 连接、操作记录
    关于前后端分离文件上传的些许问题
    代码优化--策略模式的四种表现
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/10923805.html
Copyright © 2011-2022 走看看