标签:
题目:
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
思路:这个题和number of islands差不多。也用到flood fill的思想。想不起来可以看看number of island那个日志。我们先把靠边的O都标记成一个别的字符比如N。然后剩下的O就是被X包围的。
扫描一遍board,把剩下的O标记为X。标记为别的字符的地方还原为O。
一开始用dfs的foolfill。结果超时了。。。所以改写成BFS的。思路一样。这样就能通过了。
1 public void solve(char[][] board) { 2 if (board == null || board.length == 0 || board[0].length == 0) { 3 return; 4 } 5 int rowLen = board.length; //1 6 int colLen = board[0].length; // 1 7 for (int i = 0; i < rowLen; i++) { 8 if (board[i][0] == ‘O‘) { 9 floodfill(‘N‘, i, 0, board); 10 } 11 if (board[i][colLen - 1] == ‘O‘) { 12 floodfill(‘N‘, i, colLen - 1, board); 13 } 14 } 15 for (int j = 0; j < colLen; j++) { 16 if (board[0][j] == ‘O‘) { 17 floodfill(‘N‘, 0, j, board); 18 } 19 if (board[rowLen - 1][j] == ‘O‘) { 20 floodfill(‘N‘, rowLen - 1, j, board); 21 } 22 } 23 24 for (int i = 0; i < rowLen; i++) { 25 for (int j = 0; j < colLen; j++) { 26 if (board[i][j] == ‘O‘) { 27 board[i][j] = ‘X‘; 28 } 29 if (board[i][j] == ‘N‘) { 30 board[i][j] = ‘O‘; 31 } 32 } 33 } 34 } 35 /* 36 public void floodfill(char c, int i, int j, char[][] board) { 37 if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != ‘O‘) { 38 return; 39 }else{ 40 board[i][j] = c; 41 } 42 floodfill(c, i + 1, j, board); 43 floodfill(c, i - 1, j, board); 44 floodfill(c, i, j + 1, board); 45 floodfill(c, i, j - 1, board); 46 } 47 */ 48 private static void floodfill(char c, int i, int j, char[][] board) { 49 Queue<Integer> q = new LinkedList<Integer>(); 50 int rowLen = board.length; 51 int colLen = board[0].length; 52 board[i][j] = c; 53 q.offer(i * colLen + j); 54 while (!q.isEmpty()) { 55 int index = q.poll(); 56 int row = index / colLen; 57 int col = index % colLen; 58 if (row - 1 > 0 && board[row - 1][col] == ‘O‘) { 59 board[row - 1][col] = c; 60 q.offer((row - 1) * colLen + col); 61 } 62 if (row + 1 < rowLen && board[row + 1][col] == ‘O‘) { 63 board[row + 1][col] = c; 64 q.offer((row + 1) * colLen + col); 65 } 66 if (col - 1 > 0 && board[row][col - 1] == ‘O‘) { 67 board[row][col - 1] = c; 68 q.offer(row * colLen + col - 1); 69 } 70 if (col + 1 < colLen && board[row][col + 1] == ‘O‘) { 71 board[row][col + 1] = c; 72 q.offer(row* colLen + col + 1); 73 } 74 } 75 }
标签:
原文地址:http://www.cnblogs.com/gonuts/p/4472818.html