leetCode练习(130)
来源:互联网 发布:自己动手装修房子软件 编辑:程序博客网 时间:2024/06/05 15:01
题目:Surrounded Regions
难度:medium
问题描述:
Given a 2D board containing 'X'
and 'O'
(the letter 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
解题思路:不被包围的区域就是有‘O’点在边界的区域。只要把所有边界的'O'点找出了,然后使用BFS,标记所有的未被包围的点,最后进行处理即可。
代码如下:(偷了个懒,对数组边界的判断直接使用了try catch ,效率很低~)
public class Solution { public void solve(char[][] board) { if(board==null||board.length<=1||board[0].length<=1){ return; } int row=board.length; int colum=board[0].length; Queue<int[]> queue=new ArrayDeque<>(); for(int i=0;i<colum-1;i++){ if(board[0][i]=='O'){ int[] temp=new int[2]; temp[0]=0;temp[1]=i; queue.add(temp); } } for(int i=0;i<row-1;i++){ if(board[i][colum-1]=='O'){ int[] temp=new int[2]; temp[0]=i;temp[1]=colum-1; queue.add(temp); } } for(int i=colum-1;i>=1;i--){ if(board[row-1][i]=='O'){ int[] temp=new int[2]; temp[0]=row-1;temp[1]=i; queue.add(temp); } } for(int i=row-1;i>=1;i--){ if(board[i][0]=='O'){ int[] temp=new int[2]; temp[0]=i;temp[1]=0; queue.add(temp); } } while(!queue.isEmpty()){ int[] a=queue.poll(); int x=a[0]; int y=a[1]; if(board[x][y]=='X'||board[x][y]=='i'){ continue; } board[x][y]='i'; try{ if(board[x-1][y]=='O'){ int[] temp=new int[2]; temp[0]=x-1;temp[1]=y; queue.add(temp); } }catch(Exception e){ } try{ if(board[x+1][y]=='O'){ int[] temp=new int[2]; temp[0]=x+1;temp[1]=y; queue.add(temp); } }catch(Exception e){ } try{ if(board[x][y-1]=='O'){ int[] temp=new int[2]; temp[0]=x;temp[1]=y-1; queue.add(temp); } }catch(Exception e){ } try{ if(board[x][y+1]=='O'){ int[] temp=new int[2]; temp[0]=x;temp[1]=y+1; queue.add(temp); } }catch(Exception e){ } } for(int i=0;i<row;i++){ for(int j=0;j<colum;j++){ if(board[i][j]=='X'){ continue; }else{ if(board[i][j]=='i'){ board[i][j]='O'; }else{ board[i][j]='X'; } } } } }}
0 0
- leetCode练习(130)
- leetCode练习(7)
- leetCode练习(9)
- leetCode练习(2)
- leetCode练习(14)
- leetCode练习(3)
- leetCode练习(4)
- leetCode练习(19)
- leetCode练习(18)
- leetCode练习(5)
- leetCode练习(15)
- leetCode练习(20)
- leetCode练习(21)
- leetCode练习(16)
- leetCode练习(17)
- leetCode练习(11)
- leetCode练习(24)
- leetCode练习(22)
- java的反射机制浅谈
- 视图操作
- js的数组
- oracle invalid number
- 编程规范7
- leetCode练习(130)
- LeetCode 107. Binary Tree Level Order Traversal II
- OkHttp封装类
- typedef思考
- 神经网络的机器学习(Neural Networks for Machine Learning)(7)
- linux对于互斥器的封装
- new 接口{内部实现方法} 转为 匿名内部类
- OkHttp封装类
- 登录用户的edittext高级点的样式