From 61df19551c117cdbca48b25963e60e5df490b423 Mon Sep 17 00:00:00 2001 From: xliu45 Date: Fri, 22 Apr 2016 00:46:31 -0500 Subject: [PATCH] Add 130_Surrounded_Regions.cpp --- C++/130_Surrounded_Regions.cpp | 85 ++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 C++/130_Surrounded_Regions.cpp diff --git a/C++/130_Surrounded_Regions.cpp b/C++/130_Surrounded_Regions.cpp new file mode 100644 index 00000000..c008b97e --- /dev/null +++ b/C++/130_Surrounded_Regions.cpp @@ -0,0 +1,85 @@ +//130. 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 + +Tag: Breadth-first Search, Union Find + +Author: Xinyu Liu +*/ +#include +using namespace std; + +class Solution { +public: + void solve(vector>& board) { + int i,j; + int row = board.size(); + if(!row) + return; + int col = board[0].size(); + + for(i = 0; i < row; i++){ + nearcheck(board, i, 0, row,col); + if(col > 1) + nearcheck(board, i, col - 1, row, col); + } + for(j = 1; j + 1 < col; j++){ + nearcheck(board, 0, j, row, col); + if(row > 1) + nearcheck(board, row - 1, j, row, col); + } + for(i = 0; i < row; i++) + for(j = 0; j < col; j++) + if(board[i][j] == 'O') + board[i][j] = 'X'; + for(i = 0; i < row; i++) + for(j = 0; j < col; j++) + if(board[i][j] == '1') + board[i][j] = 'O'; + } + void nearcheck(vector >&vec, int i, int j, int row, int col){ + if(vec[i][j] == 'O'){ + vec[i][j] = '1'; + if(i > 1) + nearcheck(vec, i - 1, j, row, col); + if(j > 1) + nearcheck(vec, i, j - 1, row, col); + if(i < row - 1) + nearcheck(vec, i + 1, j, row, col); + if(j < col - 1) + nearcheck(vec, i, j + 1, row, col); + } + } +}; + +void main(){ + char c0[] = {'X','X','X','X'}; + vector v0 (begin(c0), end(c0)); + char c1[] = {'X','O','O','X'}; + vector v1 (begin(c1), end(c1)); + char c2[] = {'X','X','O','X'}; + vector v2 (begin(c2), end(c2)); + char c3[] = {'X','X','X','X'}; + vector v3 (begin(c3), end(c3)); + vector> v; + v.push_back(v0); + v.push_back(v1); + v.push_back(v2); + v.push_back(v3); + Solution sol; + sol.solve(v); +}