標籤:style blog http color io 資料 for ar
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 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肯定是escape的,這樣由邊界往裡面縱深尋找出沒有被capture的O
思路1:dfs,第一次居然過了,然後就再也過不去了,試想一個矩陣是100* 100並且全是O,如果dfs的話,就會有10000層,棧空間都溢出了....
思路2:BFS,大資料無壓力過
代碼如下:
1 public class Solution { 2 public void solve(char[][] board) { 3 if(board == null || board.length == 0 ) return; 4 int height = board.length; 5 int width = board[0].length; 6 int code = Math.max(height, width); 7 for(int i = 0; i < height; i++){ 8 for(int j = 0; j < width; j++){ 9 if(board[i][j] == ‘O‘ && (i == 0 || i == height - 1 || j == 0 || j == width - 1)){10 board[i][j] = ‘@‘;11 bfs(board, height, width, i, j, code);12 }13 }14 }15 for(int i = 0; i < height; i++){16 for(int j = 0; j < width; j++){17 if(board[i][j] == ‘O‘){18 board[i][j] = ‘X‘;19 }else if(board[i][j] == ‘@‘){20 board[i][j] = ‘O‘;21 }22 }23 }24 }25 int[][] dir = {{-1,0},{1,0},{0,1},{0,-1}};26 private void bfs(char[][] board,int height,int width,int i ,int j,int code){27 Queue<Integer> q = new LinkedList<Integer>();28 q.offer(i * code + j);//將二維下標壓縮成一維,方便儲存29 while(!q.isEmpty()){30 int tem = q.poll();31 int row = tem / code;32 int col = tem % code;33 for(int k = 0;k < dir.length; k++){34 if(row + dir[k][0] < height && row + dir[k][0] >= 0 && col + dir[k][1] < width && col + dir[k][1] >= 0){35 if(board[row + dir[k][0]][col + dir[k][1]] == ‘O‘){36 board[row + dir[k][0]][col + dir[k][1]] = ‘@‘;37 q.offer((row + dir[k][0]) * code + col + dir[k][1]);38 }39 }40 }41 }42 }43 }
座標壓縮法很有意思。