Surrounded Regions
来源:互联网 发布:淘宝客服培训流程 编辑:程序博客网 时间:2024/05/17 22:07
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用BFS,记录每一个和边界O相连的O。
class Solution {public: void solve(vector<vector<char> > &board) { int width = board.size(); if (width == 0) return; int length = board[0].size(); if (length == 0) return; for (int i = 0; i < length; ++i) { if (board[0][i] == 'O') bfsBoundary(board, 0, i); if (board[width-1][i] == 'O') bfsBoundary(board, width-1, i); } for (int i = 0; i < width; ++i) { if (board[i][0] == 'O') bfsBoundary(board, i, 0); if (board[i][length-1] == 'O') bfsBoundary(board, i, length-1); } for (int i = 0; i < width; ++i) { for (int j = 0; j < length; ++j) { if (board[i][j] == 'O') board[i][j] = 'X'; else if (board[i][j] == 'B') board[i][j] = 'O'; } } } void bfsBoundary(vector<vector<char> >& board, int w, int l) { int width = board.size(); int length = board[0].size(); queue<pair<int, int> > q; q.push(pair<int, int>(w, l)); board[w][l] = 'B'; while (!q.empty()) { pair<int, int> cur = q.front(); q.pop(); int adjs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; for (int i = 0; i < 4; ++i) { int adjW = adjs[i][0] + cur.first; int adjL = adjs[i][1] + cur.second; if ((adjW >= 0) && (adjW < width) && (adjL >= 0) && (adjL < length) && (board[adjW][adjL] == 'O')) { q.push(make_pair(adjW, adjL)); board[adjW][adjL] = 'B'; } } } }};
0 0
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- SIM卡变更检验
- Mac系统里添加了仅限共享的用户账户后如何发现与删除
- 微观SOA:服务设计原则及其实践方式(上篇)
- markdown语法备忘笔记
- UITableView设置单行高度
- Surrounded Regions
- 回车与换行的区别
- c++ primer(第五版)笔记 第十三章(4) string 类和 vector<string> 容器的简单实现
- IOS kvc是神马
- Grails 笔记
- Matlab 结构体数组
- MongoDB 安装
- LeetCode ZigZag Conversion
- quickcocos2dx cocostudio的panle中添加cclayer