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

    public void Solve(char[,] board) {
            if(board.GetLength(0)==0 || board.GetLength(0)==0 ) return;
            int rowLength = board.GetLength(0);
            int colLength = board.GetLength(1);
     
            for(int i = 0;i<rowLength;i++)
            {
                for(int j = 0;j<colLength;j++)
                {
                    if((i==0||j==0||i == rowLength-1 || j == colLength -1)&&(board[i,j]=='O'))
                    {
                        DFS(board,i,j);
                    }
                }
            }
            for(int i = 0;i<rowLength;i++)
            {
                for(int j = 0;j<colLength;j++)
                {
                   if(board[i,j]=='T')  board[i,j]='O';
                   else if(board[i,j]=='O')  board[i,j]='X';
                }
            }
            return;
            
        }
        
        private void DFS(char[,] board, int row, int col)
        {
            board[row,col] = 'T';
            if(row>0 && board[row-1,col] == 'O') DFS(board,row-1,col);
            if(row<(board.GetLength(0)-1) && board[row+1,col] == 'O') DFS(board,row+1,col);
            if(col>1 && board[row,col-1] == 'O') DFS(board,row,col-1);
            if(col<(board.GetLength(1)-1) && board[row,col+1] == 'O') DFS(board,row,col+1);
        }
  • 相关阅读:
    java中next()、nextInt()、nextLine()区别
    原码、反码、补码及移位运算
    微信小程序开发流程(适用于新手学习)
    Dubbo 常用的容错机制
    分布式系统性能注意点
    陌上人如玉,公子世无双!
    五步工作法
    四个凡是
    Javacpu 和内存问题排查步骤
    开启JMC功能
  • 原文地址:https://www.cnblogs.com/renyualbert/p/5898535.html
Copyright © 2011-2022 走看看