标签:
原题链接在这里:https://leetcode.com/problems/surrounded-regions/
第一行和最后一行,第一列和最后一列,若是有‘O‘才能保留,并且和它们相连的‘O‘才能同时保留。
所以从这四条边上的‘O‘ 点开始做BFS, 把所有相连的点都变成 ‘#‘.
最后扫描一遍board, 先判定这点若还是 ‘O‘, 说明这个‘O‘没有与边界相连,即是被包围的‘O‘, 改为‘X‘.
后判定这点若是‘#‘, 说明这个‘O‘与边界相连,应该保存,改回‘O‘.
AC Java:
1 public class Solution { 2 public void solve(char[][] board) { 3 if(board == null || board.length == 0 || board[0].length == 0){ 4 return; 5 } 6 for(int i = 0; i<board[0].length; i++){ 7 if(board[0][i] == ‘O‘){ 8 bfs(board,0,i); 9 } 10 if(board[board.length-1][i] == ‘O‘){ 11 bfs(board,board.length-1,i); 12 } 13 } 14 for(int i = 0; i<board.length; i++){ 15 if(board[i][0] == ‘O‘){ 16 bfs(board,i,0); 17 } 18 if(board[i][board[0].length - 1] == ‘O‘){ 19 bfs(board,i,board[0].length-1); 20 } 21 } 22 for(int i = 0; i<board.length; i++){ 23 for(int j = 0; j<board[0].length; j++){ 24 if(board[i][j] == ‘O‘){ 25 board[i][j] = ‘X‘; 26 } 27 if(board[i][j] == ‘#‘){ 28 board[i][j] = ‘O‘; 29 } 30 } 31 } 32 } 33 34 private void bfs(char[][] board, int i, int j){ 35 if(board[i][j] != ‘O‘){ 36 return; 37 } 38 board[i][j] = ‘#‘; 39 LinkedList<Integer> que = new LinkedList<Integer>(); 40 int n = board[0].length; 41 int code = calCode(board,i,j); 42 que.offer(code); 43 while(!que.isEmpty()){ 44 int temp = que.poll(); 45 int row = temp/n; 46 int col = temp%n; 47 if(row>=1 && board[row-1][col] == ‘O‘){ 48 board[row-1][col] = ‘#‘; 49 que.add(calCode(board,row-1,col)); 50 } 51 if(row<=board.length-2 && board[row+1][col] == ‘O‘){ 52 board[row+1][col] = ‘#‘; 53 que.add(calCode(board,row+1,col)); 54 } 55 if(col >=1 && board[row][col-1] == ‘O‘){ 56 board[row][col-1] = ‘#‘; 57 que.add(calCode(board,row,col-1)); 58 } 59 if(col <=board[0].length-2 && board[row][col+1] == ‘O‘){ 60 board[row][col+1] = ‘#‘; 61 que.add(calCode(board,row,col+1)); 62 } 63 } 64 } 65 private int calCode(char[][] board, int i, int j){ 66 return i*board[0].length + j; 67 } 68 }
标签:
原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/4886925.html