zoukankan      html  css  js  c++  java
  • LeetCode_Surrounded Regions

    Given a 2D board containing 'X' and '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
    

      solution: 思想是mark 出所有外围的O,里面的不管。

    1. First scan the four edges of the board, if you meet an 'O', call a recursive mark function to mark that region to something else (for example, '+');
    2. scan all the board, if you meet an 'O', flip it to 'X';
    3. scan again the board, if you meet an '+', flip it to 'O';
      class Solution {
      public:
           void BFS(vector<vector<char>> &board, int i , int j){
          
              if(board[i][j] == 'X' || board[i][j] == '#') return;
              board[i][j] = '#';
        
              if( i -1 >= 0 ) BFS(board, i-1, j );
              if( i + 1 <  rows  ) BFS(board, i+1, j ); 
              if( j -1 >= 0 ) BFS(board, i, j-1 );
              if( j +1 < columns ) BFS(board, i, j+1 );
          }
          void solve(vector<vector<char>> &board) {
              // Start typing your C/C++ solution below
              // DO NOT write int main() function
              rows = board.size();
              if( rows == 0) return ;
              columns = board[0].size();
              if(columns == 0) return ;
              
              for( int i = 1; i < columns - 1 ; i++)
              {
                  BFS(board, 0,i);//up
                  BFS(board, rows - 1 , i );//down
              }
              for( int i = 0; i< rows; i++)
              {
                  BFS(board, i, 0 ); //left
                  BFS(board, i, columns - 1); //right
              }
              for(int i = 0; i< rows; i++)
                  for(int j = 0; j < columns ; j++)
                  {
                    if(board[i][j] == '#') 
                       board[i][j] = 'O';
                    else if (board[i][j] == 'O')
                      board[i][j] = 'X';
                  }    
          }
      private :
          int rows;
          int columns;
      };
  • 相关阅读:
    用Java来获取访问者真实的IP地址
    springMVC 配置多个视图解析器
    java 内部类(inner class)详解
    安装mysql步骤
    Jquery 获取父页面下指定iframe里的指定元素
    Oracle 中文排序
    Oracle update时做表关联
    Jquery IE8兼容性
    JQuery 动态创建表单,并自动提交
    JQuery 使用.show()和.hide()做的可爱动画
  • 原文地址:https://www.cnblogs.com/graph/p/3251354.html
Copyright © 2011-2022 走看看