leetcode130 - Surrounded Regions - medium
Given a 2D board containing 'X' and 'O' (the letter 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 X X X
X O O X -> X X X X
X X O X X X X X
X O X X X O X X
BFS。
问题转换:问题是找被X包围在内保护起来的O,正向找外界碰不到的O不好找,那就反向转化为找外界能连通到的O。那如果对边缘一圈的O做BFS,碰到的O肯定都是能连到地图外的O,那就标记为‘W’(灌水)。最后再遍历一次地图,让所有被灌水的回到‘O’,其他的都归为‘X’即可。
写一个某一个O向四周不断bfs标记其他O的子函数。主函数里对上下左右四条边的O进行bfs即可(bfs里隐式让看到非O就返回退出,能让主函数更简洁)。
细节:棋盘题进行上下左右移动可以借助int[] dx = {0, -1, 0, 1}; int[] dy = {-1, 0, 1, 0}; ,之后for(4) {newX = x + dx[i], newY = y + dy[i]}来做。
实现:
class Solution { public void solve(char[][] board) { if (board == null || board.length == 0 || board[0].length == 0) { return; } for (int i = 0; i < board.length; i++) { bfs(board, i, 0); bfs(board, i, board[0].length - 1); } for (int j = 0; j < board[0].length; j++) { bfs(board, 0, j); bfs(board, board.length - 1, j); } for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { if (board[i][j] == 'W') { board[i][j] = 'O'; } else if (board[i][j] == 'O') { board[i][j] = 'X'; } } } } private void bfs(char[][] board, int x, int y) { if (board[x][y] != 'O') { return; } board[x][y] = 'W'; int[] dx = {0, 1, 0, -1}; int[] dy = {1, 0, -1, 0}; Queue<Integer> qx = new LinkedList<>(); Queue<Integer> qy = new LinkedList<>(); qx.offer(x); qy.offer(y); while (!qx.isEmpty()) { int cx = qx.poll(); int cy = qy.poll(); for (int i = 0; i < 4; i++) { int nx = cx + dx[i]; int ny = cy + dy[i]; if (nx >= 0 && nx < board.length && ny >= 0 && ny < board[0].length && board[nx][ny] == 'O') { board[nx][ny] = 'W'; qx.offer(nx); qy.offer(ny); } } } } }