leetcoe || 130、Surrounded Regions
来源:互联网 发布:淘宝嘉年华公告在哪看 编辑:程序博客网 时间:2024/06/10 06:00
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 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 XBreadth-first Search
题意:将被X包围的O换成X
thinking:
(1)首先我用递归做的,提交栈溢出了....
(2)参考网上的实现,要用到一种图形学的算法:泛洪算法-维基
采用BFS或者DFS,使用queue或者stack结构。
code:
class Solution {public: int row; int col; void bfs(vector<vector<char> > &board, int r, int c) { queue<pair<int, int> > qe; qe.push({r, c}); while(!qe.empty()) { r = qe.front().first; c = qe.front().second; qe.pop(); if (r>0&&board[r-1][c]=='O') { board[r-1][c] = '+'; qe.push({r-1,c}); } if (r+1<row&&board[r+1][c]=='O') { board[r+1][c] = '+'; qe.push({r+1,c}); } if (c>0&&board[r][c-1]=='O') { board[r][c-1] = '+'; qe.push({r,c-1}); } if (c+1<col&&board[r][c+1]=='O') { board[r][c+1] = '+'; qe.push({r,c+1}); } } return; } void solve(vector<vector<char> > &board) { if (board.empty()) return; row = board.size(); col = board[0].size(); // top edge for(int i = 0; i < col; ) { if(board[0][i] == 'O') { int j=i; while(board[0][j]=='O') j++; board[0][i] = '+'; bfs(board, 0, i); i = j; } else i++; } // bottom edge for(int i = 0; i < col;) { if(board[row-1][i] == 'O') { int j=i; while(board[row-1][j]=='O') j++; board[row-1][i] = '+'; bfs(board, row-1, i); i = j; } else i++; } // left edge for(int i = 1; i < row-1;) { if(board[i][0] == 'O') { int j=i; while(board[j][0]=='O') j++; board[i][0] = '+'; bfs(board, i, 0); i = j; } else i++; } // right edge for(int i = 1; i < row-1; ) { if(board[i][col-1] == 'O') { int j=i; while(board[j][col-1]=='O') j++; board[i][col-1] = '+'; bfs(board, i, col-1); i = j; } else i++; } // then scan all the cells, recover live cells and flip dead cells for(int i = 0; i < row; i++) for(int j = 0; j < col; j++) board[i][j] = (board[i][j]=='+')?'O':'X'; return; }};
0 0
- leetcoe || 130、Surrounded Regions
- LeetCode: Surrounded Regions [130]
- LeetCode(130) Surrounded Regions
- [leetcode 130] Surrounded Regions
- 130:Surrounded Regions【BFS】
- LeetCode 130 Surrounded Regions
- Leetcode 130 Surrounded Regions
- LeetCode(130) Surrounded Regions
- leetcode 130: Surrounded Regions
- Leetcode #130 Surrounded Regions
- 130 Surrounded Regions [Leetcode]
- leetcode 130: Surrounded Regions
- LeetCode 130 Surrounded Regions
- 130Surrounded Regions
- LeetCode 130 Surrounded Regions
- Leetcode 130 Surrounded Regions
- LeetCode -130-Surrounded Regions
- [Leetcode] #130 Surrounded Regions
- 大家有哪些好的android开发习惯?
- [G+smo]gsFunction
- java.util.ConcurrentModificationException 出现的原因和解决办法
- 分类组合计划 - Assortment Planning
- 麦讯通接口开发api文档
- leetcoe || 130、Surrounded Regions
- 单链表就地逆置
- FileZilla Server源码分析--大漠落日5节
- 各种序列化反序列化操作时间对比
- 工作态度的重要性
- 消息对话框
- 中值滤波器
- leetcode最近的一题:count primes
- 所谓的自动执行sql脚本小程序,c/c++连接sybase