首页 > 代码库 > Surrounded Regions
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 XX O O XX X O XX O X X
After running your function, the board should be:
X X X XX X X XX X X XX O X X
分析:解此题的关键是发现一条隐含的规律:如果一个‘O’不能被‘X‘包围的话,那么与该‘O’相邻的其他‘O‘也不能被‘X‘包围。而且所有不能被‘X‘包围的‘O‘都起始于board的四个边缘。因为我们可以用搜索的方法标注所有不能被‘X‘包围的‘O’,标注完成后,再遍历一遍board把未被标注的‘O‘改为‘X’。遍历的可以用bfs和dfs,但当board比较大时dfs递归层数太多会引起runtime error,所以bfs对于大数据比较合适。
dfs代码:
class Solution {public: void solve(vector<vector<char>> &board) { int m = board.size(); if(m == 0) return; int n = board[0].size(); if(n == 0) return; for(int i = 0; i < n; i++) if(board[0][i] == ‘O‘) dfs(board, 0, i); for(int i = 1; i < m-1; i++) if(board[i][0] ==‘O‘) dfs(board, i, 0); for(int i = 1; i < m-1; i++) if(board[i][n-1] == ‘O‘) dfs(board, i, n-1); for(int i = 0; i < n; i++) if(board[m-1][i] == ‘O‘) dfs(board, m-1, i); for(int i = 0; i < m; i++) for(int j = 0; j < n; j++){ if(board[i][j] == ‘O‘) board[i][j] = ‘X‘; else if(board[i][j] == ‘+‘) board[i][j] = ‘O‘; } } void dfs(vector<vector<char>> &board, int i, int j){ board[i][j] = ‘+‘; if(i > 0 && board[i-1][j] == ‘O‘) dfs(board, i-1, j); if(i < board.size()-1 && board[i+1][j] == ‘O‘) dfs(board, i+1, j); if(j > 0 && board[i][j-1] == ‘O‘) dfs(board, i, j-1); if(j < board[0].size()-1 && board[i][j+1] == ‘O‘) dfs(board, i, j+1); }};
bfs代码:
class Solution {public: void solve(vector<vector<char>> &board) { int m = board.size(); if(m == 0) return; int n = board[0].size(); if(n == 0) return; for(int i = 0; i < n; i++) if(board[0][i] == ‘O‘) bfs(board, 0, i); for(int i = 1; i < m-1; i++) if(board[i][0] ==‘O‘) bfs(board, i, 0); for(int i = 1; i < m-1; i++) if(board[i][n-1] == ‘O‘) bfs(board, i, n-1); for(int i = 0; i < n; i++) if(board[m-1][i] == ‘O‘) bfs(board, m-1, i); for(int i = 0; i < m; i++) for(int j = 0; j < n; j++){ if(board[i][j] == ‘O‘) board[i][j] = ‘X‘; else if(board[i][j] == ‘+‘) board[i][j] = ‘O‘; } } void bfs(vector<vector<char>> &board, int i, int j){ queue<pair<int, int>> Q; board[i][j] = ‘+‘; Q.push(make_pair(i,j)); while(!Q.empty()){ auto tmp = Q.front(); Q.pop(); if(tmp.first > 0 && board[tmp.first-1][tmp.second] == ‘O‘){ board[tmp.first-1][tmp.second] = ‘+‘; Q.push(make_pair(tmp.first-1,tmp.second)); } if(tmp.first < board.size()-1 && board[tmp.first+1][tmp.second] == ‘O‘){ board[tmp.first+1][tmp.second] = ‘+‘; Q.push(make_pair(tmp.first+1,tmp.second)); } if(tmp.second > 0 && board[tmp.first][tmp.second-1] == ‘O‘){ board[tmp.first][tmp.second-1] = ‘+‘; Q.push(make_pair(tmp.first,tmp.second-1)); } if(tmp.second < board[0].size()-1 && board[tmp.first][tmp.second+1] == ‘O‘){ board[tmp.first][tmp.second+1] = ‘+‘; Q.push(make_pair(tmp.first,tmp.second+1)); } } }};
Surrounded Regions
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。