[leetcode]Surrounded Regions

來源:互聯網
上載者:User

標籤: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 }

座標壓縮法很有意思。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.