Given a 2D Board containing‘X‘
And‘O‘
, Capture all regions surrounded‘X‘
.
A region is captured by flipping all‘O‘
S‘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 shoshould be:
X X X XX X X XX X X XX O X X
Problem: BFS is used.
The peripheral o cannot be changed to X, and these o can be pushed into a queue, and then the breadth is first searched from top to bottom and left, the O around them does not need to be changed to X (because it has a path of o that breaks out), and then continues to search for the o from the surrounding points ......
Implementation Details:
- Use a visited two-dimensional array to record whether an O has been in the queue, so that it does not have an endless loop;
- In another two-dimensional array, ISX records vertices that do not need to be converted to X. After BFS ends, all vertices to be converted to X are converted to X;
- In the question, both X and O are uppercase =. =
The implementation code is as follows:
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 queue20 Queue<co> queue = new LinkedList<co>();21 22 //first line and last line23 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 column38 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 //up54 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 //down60 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 //left66 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 //right72 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 }
[Leetcode questions and Notes] surrounded regions