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
原创粉丝点击