leetcode 130: Surrounded Regions
来源:互联网 发布:域名污染 gfw 编辑:程序博客网 时间:2024/05/16 17:58
The algorithm is not so hard to think. Just try from the boarder, if there is an 'O', DFS or BFS and change all 'O's in that region to another character. After that, change all 'O's to 'X' and all different characters (I use 'n') to 'O'. The trick when using BFS here is to change the character before push into the queue, or it will push some positions that are already in the queue and finally cause TLE.
class Solution {public: void solve(vector<vector<char>>& board) { if(board.empty()) return; int m=board.size(); int n=board[0].size(); for(int i=0;i<m;i++) { if(board[i][0]=='O') bfs(board,i,0,m,n); if(board[i][n-1]=='O') bfs(board,i,n-1,m,n); } for(int i=0;i<n;i++) { if(board[0][i]=='O') bfs(board,0,i,m,n); if(board[m-1][i]=='O') bfs(board,m-1,i,m,n); } 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]=='n') board[i][j]='O'; } } void bfs(vector<vector<char> >& board,int r,int c,int m,int n) { queue<pair<int,int> > q; board[r][c]='n'; q.push(make_pair(r,c)); while(!q.empty()) { r=q.front().first; c=q.front().second; q.pop(); if(r>0&&board[r-1][c]=='O') { board[r-1][c]='n'; q.push(make_pair(r-1,c)); } if(r<m-1&&board[r+1][c]=='O') { board[r+1][c]='n'; q.push(make_pair(r+1,c)); } if(c>0&&board[r][c-1]=='O') { board[r][c-1]='n'; q.push(make_pair(r,c-1)); } if(c<n-1&&board[r][c+1]=='O') { board[r][c+1]='n'; q.push(make_pair(r,c+1)); } } }};
0 0
- LeetCode: Surrounded Regions [130]
- LeetCode(130) Surrounded Regions
- [leetcode 130] Surrounded Regions
- 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
- LeetCode 130 Surrounded Regions
- Leetcode 130 Surrounded Regions
- LeetCode -130-Surrounded Regions
- [Leetcode] #130 Surrounded Regions
- [Leetcode 130, medium] Surrounded regions
- [leetcode-130]Surrounded Regions(java)
- (LeetCode 130) Surrounded Regions(BFS)
- Quartz.Net定时任务框架,实现灵活的定时任务
- Unity Manual之Rigidbody 刚体
- R语言抓取pm2.5数据绘制全国pm2.5分布图
- IO流笔记01
- Linux学习笔记:系统启动引导过程
- leetcode 130: Surrounded Regions
- ListView的工作原理及优化
- Unity_角色控制详解
- Oracle清理回收站的方法
- TYVJ 1330 乳草的入侵
- /sys/class/gpio 文件接口操作IO端口(s3c2440)
- CSS3属性box-flex
- hdoj5253
- OC_Notifications(通知)