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,里面的不管。
- 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, '+');
- scan all the board, if you meet an 'O', flip it to 'X';
- 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; };
--------------------------------------------------------------------天道酬勤!
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步