Problem
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
Code
void solve(vector<vector<char>> &board) { // Note: The Solution object is instantiated only once and is reused by each test case. int m = board.size(); if(m == 0) return; int n = board[0].size(); vector<vector<bool> > M(m,vector<bool>(n,true)); for(int j = 0;j < n; ++j){ M[0][j] = (board[0][j] == 'X'); M[m - 1][j] = (board[m - 1][j] == 'X'); } for(int i = 1;i < m - 1; ++i){ M[i][0] = (board[i][0] == 'X'); M[i][n - 1] = (board[i][n - 1] == 'X'); } bool falseFound = true; while(falseFound){ falseFound = false; for(int i = 1;i < m - 1; ++i){ for(int j = 1;j < n - 1; ++j){ if(board[i][j] == 'O' && M[i][j]){ if(!(M[i][j - 1] && M[i - 1][j])){ M[i][j] = false; falseFound = true; } } } } for(int i = m - 2;i > 0; --i){ for(int j = n - 2;j > 0; --j){ if(board[i][j] == 'O' && M[i][j]){ if(!(M[i][j + 1] && M[i + 1][j])){ M[i][j] = false; falseFound = true; } } } } } for(int i = 0;i < m ; ++i){ for(int j = 0;j < n ; ++j){ if(M[i][j]) board[i][j] = 'X'; else board[i][j] = 'O'; } } }
No comments:
Post a Comment