130 Surrounded Regions [Leetcode]
2015-10-02 20:45
330 查看
题目内容:
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,
After running your function, the board should be:
题目分析:
有两种切入点,一种是查找被围起来的区域,将他们标成’X’,另一种是找边界上的’O’,用排除法,剩下的就是被围起来的区域。
这两种方法都可以用BFS实现,我使用了找边界上与’O’连通的区域,将他们存储到一个队列中,然后使用BFS,找到所有的连通点,设置一个特殊的标志’-‘,最后遍历一遍,将所有的’O’改为’X’,将所有的’-‘改为’O’。
代码实现:
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
题目分析:
有两种切入点,一种是查找被围起来的区域,将他们标成’X’,另一种是找边界上的’O’,用排除法,剩下的就是被围起来的区域。
这两种方法都可以用BFS实现,我使用了找边界上与’O’连通的区域,将他们存储到一个队列中,然后使用BFS,找到所有的连通点,设置一个特殊的标志’-‘,最后遍历一遍,将所有的’O’改为’X’,将所有的’-‘改为’O’。
代码实现:
class Solution { public: void solve(vector<vector<char>>& board) { if(board.size() == 0) return; int row(board.size()), col(board[0].size()), r, c; queue<int> index_x, index_y; for(int i = 0; i < col; ++i) { if(board[0][i] == 'O') { index_x.push(0); index_y.push(i); } if(board[row-1][i] == 'O') { index_x.push(row-1); index_y.push(i); } } for(int i = 1; i < row-1; ++i) { if(board[i][0] == 'O') { index_x.push(i); index_y.push(0); } if(board[i][col-1] == 'O') { index_x.push(i); index_y.push(col-1); } } while(!index_x.empty()) { r = index_x.front(); c = index_y.front(); index_x.pop(); index_y.pop(); board[r][c] = '-'; if(r > 0 && board[r-1][c] == 'O') { index_x.push(r-1); index_y.push(c); } if(r < row-1 && board[r+1][c] == 'O') { index_x.push(r+1); index_y.push(c); } if(c > 0 && board[r][c-1] == 'O') { index_x.push(r); index_y.push(c-1); } if(c < col-1 && board[r][c+1] == 'O') { index_x.push(r); index_y.push(c+1); } } for(int i = 0; i < row; ++i) { for(int j = 0; j < col; ++j) { if(board[i][j] == 'O') board[i][j] = 'X'; if(board[i][j] == '-') board[i][j] = 'O'; } } } };
相关文章推荐
- hdu 1429 胜利大逃亡(续)
- java回收机制
- mysql索引失效的情形
- svn命令
- 【Python之旅】第四篇(四):基于面向对象的模拟人生游戏类
- poj 2155 Matrix
- LeetCode题解:Convert Sorted Array to Binary Search Tree
- HTML学习记录<三> :创建电子邮件链接
- 常用host文件,提高访问速度
- Generics and Wildcards in Java
- 学习ThinkPHP3.2.2:几种URL访问方式
- HTML学习记录<二>:标签的 target 属性中的_blank _self _parent _top
- Java学习笔记----匿名对象
- hduacm 5480 Conturbatio前缀和
- python中使用re.sub更换倒数第一个字符串
- ==和equal()的区别
- 第二十六篇:通知中心 NSNotificationCenter
- 抽象类和接口的区别
- 反射3:利用java反射技术将查询结果封装成对象
- 统计文件行数