[LeetCode]Surrounded Regions
2014-03-09 13:41
399 查看
Given a 2D board containing
A region is captured by flipping all
For example,
After running your function, the board should be:
'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
class Solution { public: int dir[4][2] = {{0,1},{0,-1},{1,0},{-1,0}}; void solveUtil(vector<vector<char> >& board, vector<vector<bool> >& visited, int ix, int iy, vector<pair<int,int> >& curPath, bool& isSurrounded) { int n = board.size(); int m = board[0].size(); queue<pair<int,int> > posQ; posQ.push(pair<int,int>(ix, iy)); while(!posQ.empty()) { int curX = posQ.front().first; int curY = posQ.front().second; posQ.pop(); if(board[curX][curY] == 'O' && !visited[curX][curY]) { curPath.push_back(pair<int,int>(curX, curY)); visited[curX][curY] = true; for(int k = 0; k < 4; ++k) { int newX = curX+dir[k][0]; int newY = curY+dir[k][1]; if(newX < 0 || newX >= n || newY < 0 || newY >= m) isSurrounded = false; else if (!visited[newX][newY]) posQ.push(pair<int,int>(newX, newY)); } } } } void solve(vector<vector<char>> &board) { // Start typing your C/C++ solution below // DO NOT write int main() function int n = board.size(); if(n == 0) return; int m = board[0].size(); vector<vector<bool> > visited(n, vector<bool>(m, false)); for(int i = 0; i < n; ++i) { for(int j = 0; j < m; ++j) { vector<pair<int, int> > curPath; bool isSurrounded = true; if(!visited[i][j]) solveUtil(board, visited, i, j, curPath, isSurrounded); if(isSurrounded) { for(int i = 0; i < curPath.size(); ++i) board[curPath[i].first][curPath[i].second] = 'X'; } } } } };
相关文章推荐
- NYOJ 291 LK数学题(欧拉函数)
- HDU 1695 GCD(欧拉函数+容斥原理)
- 逆向分析技术总结(转)
- .Net MVC 网站中配置文件的读写
- Unix 編譯藝術之一:Unix歷史
- Cloud Computing Companies
- c# ConfigurationManager
- Hyper-V升级系列PART5:2012 Hyper-V群集升级至2012 R2
- android---------ndk中的各个版本的下载地址。
- 当android调试遇到ADB server didn't ACK以及顽固的sjk_daemon进程
- 15. Google面试题:在一个字符串中找到第一个只出现一次的字符。如输入abaccdeff,则输出b
- 线程通信机制:共享内存 VS 消息传递
- git 常用命令
- Hyper-V升级系列PART4:2012 Hyper导入虚拟机
- Android客户端连接Struts2服务器,连接不上的几个原因
- open和fopen的区别(转)
- C++中实现通用数据结构(转)
- snprintf() 替代 sprintf()
- linux 快捷键总结
- Leetcode_Add Two Numbers