【leetcode刷题笔记】Surrounded Regions
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 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
题解:用的BFS。
最外围的O肯定是没法变成X的,把这些O推进一个队列里面,然后从它们开始上下左右进行广度优先搜索,它们周围的O也是不用变成X的(因为它有一条突围出去的都是O的路径),然后从周围的点继续广搜......
实现细节:
- 用一个visited二维数组记录某个O是否已经进过队列了,这样就不会死循环;
- 另一个二维数组isX记录哪些点不用变成X,在BFS结束后,把要变成X的点都变成X;
- 题目中X和O都是大写的=。=
实现代码如下:
1 public class Solution { 2 class co{ 3 int x; 4 int y; 5 public co(int x,int y){ 6 this.x = x; 7 this.y = y; 8 } 9 } 10 public void solve(char[][] board) { 11 if(board == null || board.length == 0) 12 return; 13 int m = board.length; 14 int n = board[0].length; 15 boolean[][] visited = new boolean[m][n]; 16 boolean[][] isX = new boolean[m][n]; 17 for(boolean[] row:isX) 18 Arrays.fill(row, true); 19 //put all o's cordinates into queue 20 Queue<co> queue = new LinkedList<co>(); 21 22 //first line and last line 23 for(int i = 0;i < n;i++) 24 { 25 if(board[0][i]=='O'){ 26 queue.add(new co(0, i)); 27 visited[0][i]= true; 28 isX[0][i]= false; 29 } 30 if(board[m-1][i]=='O'){ 31 queue.add(new co(m-1, i)); 32 visited[m-1][i]= true; 33 isX[m-1][i]= false; 34 } 35 } 36 37 //first and last column 38 for(int j = 0;j<m;j++){ 39 if(board[j][0]=='O'){ 40 queue.add(new co(j, 0)); 41 visited[j][0]= true; 42 isX[j][0]= false; 43 } 44 if(board[j][n-1]=='O'){ 45 queue.add(new co(j,n-1)); 46 visited[j][n-1]= true; 47 isX[j][n-1]= false; 48 } 49 } 50 51 while(!queue.isEmpty()){ 52 co c = queue.poll(); 53 //up 54 if(c.x >= 1 && board[c.x-1][c.y] == 'O'&&!visited[c.x-1][c.y]){ 55 visited[c.x-1][c.y] = true; 56 isX[c.x-1][c.y] = false; 57 queue.add(new co(c.x-1, c.y)); 58 } 59 //down 60 if(c.x+1<m && board[c.x+1][c.y]=='O' && !visited[c.x+1][c.y]){ 61 visited[c.x+1][c.y] = true; 62 isX[c.x+1][c.y]= false; 63 queue.add(new co(c.x+1, c.y)); 64 } 65 //left 66 if(c.y-1>=0 && board[c.x][c.y-1]=='O' && !visited[c.x][c.y-1]){ 67 visited[c.x][c.y-1] = true; 68 isX[c.x][c.y-1] = false; 69 queue.add(new co(c.x, c.y-1)); 70 } 71 //right 72 if(c.y+1<n && board[c.x][c.y+1] == 'O' && !visited[c.x][c.y+1]){ 73 visited[c.x][c.y+1] = true; 74 isX[c.x][c.y+1] = false; 75 queue.add(new co(c.x, c.y+1)); 76 } 77 } 78 for(int i = 0;i < m;i++){ 79 for(int j = 0;j < n;j++){ 80 if(isX[i][j] ) 81 board[i][j]= 'X'; 82 } 83 } 84 return; 85 } 86 }