130. Surrounded Regions
思路是这样的:
1.把连着边缘上'O'的全部标成'#'
2.把所有没有变成'#'的'O'变成’X‘
3.把所有’#‘变回‘O’
算法是FloodFill
算法是这个意思,假如有一个格子板,从某一个格子出发,把连在一起并且没有涂过色的格子都涂上某个颜色。
ref: https://zh.wikipedia.org/wiki/Flood_fill
1 void flood_fill(int x,int y,int color) 2 { 3 area[x][y]=color; 4 if(x>0&&area[x-1][y]==0)flood_fill(x-1,y,color); 5 if(y>0&&area[x][y-1]==0)flood_fill(x,y-1,color); 6 if(x<MAX_X&&area[x+1][y]==0)flood_fill(x+1,y,color); 7 if(y<MAX_Y&&area[x][y+1]==0)flood_fill(x,y+1,color); 8 9 }
这道题就是这个变种。同时,ff算法也是bfs的变种
第一次我用递归写的,会超过overflow,所以只能用iterative写
1 public void solve(char[][] board) { 2 if(board == null || board.length == 0 || board[0].length == 0) { 3 return; 4 } 5 boolean[][] visited = new boolean[board.length][board[0].length]; 6 LinkedList<List<Integer>> queue = new LinkedList<List<Integer>>(); 7 int rowNum = board.length; 8 int colNum = board[0].length; 9 for(int i = 0; i < board.length; i++) { 10 if(board[i][0] == 'O') { 11 List<Integer> point = Arrays.asList(i, 0); 12 queue.add(point); 13 } 14 if(board[i][colNum - 1] == 'O') { 15 List<Integer> point = Arrays.asList(i, colNum - 1); 16 queue.add(point); 17 } 18 } 19 for(int i = 0; i < board[0].length; i++) { 20 if(board[0][i] == 'O') { 21 List<Integer> point = Arrays.asList(0, i); 22 queue.add(point); 23 } 24 if(board[rowNum - 1][i] == 'O') { 25 List<Integer> point = Arrays.asList(rowNum - 1, i); 26 queue.add(point); 27 } 28 } 29 fill(board, queue); 30 for(int i = 0; i < board.length; i++) { 31 for(int j = 0; j < board[0].length; j++) { 32 if(board[i][j] == '#') { 33 board[i][j] = 'O'; 34 } else if(board[i][j] == 'O') { 35 board[i][j] = 'X'; 36 } 37 } 38 } 39 } 40 41 private void fill(char[][] board, LinkedList<List<Integer>> queue) { 42 int maxRow = board.length; 43 int maxCol = board[0].length; 44 while(!queue.isEmpty()) { 45 List<Integer> cur = queue.poll(); 46 int row = cur.get(0); 47 int col = cur.get(1); 48 board[row][col] = '#'; 49 if(row > 0 && board[row - 1][col] == 'O') { 50 queue.offer(Arrays.asList(row - 1, col)); 51 } 52 if(col > 0 && board[row][col - 1] == 'O') { 53 queue.offer(Arrays.asList(row, col - 1)); 54 } 55 if(row < maxRow - 1 && board[row + 1][col] == 'O') { 56 queue.offer(Arrays.asList(row + 1, col)); 57 } 58 if(col < maxCol - 1 && board[row][col + 1] == 'O') { 59 queue.offer(Arrays.asList(row, col + 1)); 60 } 61 } 62 }
对于队列中的点,code ganker君是用给点编码,再解码,但是我就直接存的横竖坐标这样…………