[LeetCode]Surrounded Regions
dfs竟然超出栈空间,只好改用dfs
public class Solution { public void solve(char[][] board) { int row = board.length; if (row == 0) { return; } int col = board[0].length; boolean[][] record = new boolean[row][col]; Queue<Integer[]> queue = new LinkedList<Integer[]>(); for (int r = 0; r < row; r++) { if (board[r][0] == 'O' && !record[r][0]) { queue.offer(new Integer[]{r, 0}); } if (board[r][col - 1] == 'O' && !record[r][col - 1]) { queue.offer(new Integer[]{r, col - 1}); } } for (int c = 0; c < col; c++) { if (board[0][c] == 'O' && !record[0][c]) { queue.offer(new Integer[]{0, c}); } if (board[row - 1][c] == 'O' && !record[row - 1][c]) { queue.offer(new Integer[]{row - 1, c}); } } while (!queue.isEmpty()) { Integer[] node = queue.poll(); int r = node[0]; int c = node[1]; if (record[r][c]) { continue; } else { record[r][c] = true; if (r > 0 && board[r - 1][c] == 'O' && !record[r - 1][c]) { queue.offer(new Integer[]{r - 1, c}); } if (r + 1 < board.length && board[r + 1][c] == 'O' && !record[r + 1][c]) { queue.offer(new Integer[]{r + 1, c}); } if (c > 0 && board[r][c - 1] == 'O' && !record[r][c - 1]) { queue.offer(new Integer[]{r, c - 1}); } if (c + 1 < board[0].length && board[r][c + 1] == 'O' && !record[r][c + 1]) { queue.offer(new Integer[]{r, c + 1}); } } } for (int r = 0; r < row; r++) { for (int c = 0; c < col; c++) { if (board[r][c] == 'O' && !record[r][c]) { board[r][c] = 'X'; } } } } }