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.
Example
X X X X
X O O X
X X O X
X O X X
After capture all regions surrounded by 'X'
, the board should be:
X X X X
X X X X
X X X X
X O X X
BFS。问题转换:一个0被x包围,等价于其不能连到地图外面。那如果对边缘一圈的O做BFS,碰到的O肯定都是能连到地图外的O,那就标记为‘W’(灌水)。最后再遍历一次地图,让所有被灌水的回到‘O’,其他的都归为‘X’即可。
数据结构:二维数组,统一一下函数都x,y传,数组调用都int[y][x],x和w比y和h比,这样没问题。
细节:棋盘题进行上下左右移动可以借助int[] dx = {0, -1, 0, 1}; int[] dy = {-1, 0, 1, 0}; ,之后for(4) {newX = x + dx[i], newY = y + dy[i]}来做。
public class Solution { /* * @param board: board a 2D board containing 'X' and 'O' * @return: nothing */ public void surroundedRegions(char[][] board) { // write your code here if (board.length == 0 || board[0].length == 0) { return; } int h = board.length; int w = board[0].length; for (int i = 0; i < w; i++) { bfs(board, 0, i); bfs(board, h - 1, i); } for (int j = 0; j < h; j++) { bfs(board, j, 0); bfs(board, j, w - 1); } for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { if (board[j][i] == 'W') { board[j][i] = 'O'; } else { board[j][i] = 'X'; } } } } private void bfs(char[][] board, int sy, int sx) { if (board[sy][sx] == 'X') { return; } int h = board.length; int w = board[0].length; // 别写成0101 int[] dx = {0, -1, 0, 1}; int[] dy = {-1, 0, 1, 0}; board[sy][sx] = 'W'; for (int i = 0; i < 4; i++) { int cy = sy + dy[i]; int cx = sx + dx[i]; if (cx >= 0 && cx < w && cy >= 0 && cy < h && board[cy][cx] == 'O') { bfs(board, cy, cx); } } } }