我觉得这道题和传统的用动规或者贪心等算法的题目不同。按照题目的意思,就是将被‘X’围绕的‘O’区域找出来,然后覆盖成‘X’。
那问题就变成两个子问题:
1. 找到‘O’区域,可能有多个区域,每个区域‘O’都是相连的;
2. 判断‘O’区域是否是被‘X’包围。
我采用树的宽度遍历的方法,找到每一个‘O’区域,并为每个区域设置一个value值,为0或者1,1表示是被‘X’包围,0则表示不是。是否被‘X’包围就是看‘O’区域的边界是否是在2D数组的边界上。
下面是具体的AC代码:
class BoardNode{ int x; int y; public BoardNode(int x, int y){ this.x = x; this.y = y; } }
1 /** 2 * Given a 2D board containing ‘X‘ and ‘O‘, capture all regions surrounded by ‘X‘. 3 * A region is captured by flipping all ‘O‘s into ‘X‘s in that surrounded region. 4 * @param board 5 */ 6 public void solve(char[][] board){ 7 //empty 2D board 8 if(board.length == 0) 9 return; 10 //if value == 1,means the group is surrended by ‘X‘, if value == 0 , means it is not 11 HashMap<LinkedList<BoardNode>, Integer> groups = new HashMap<LinkedList<BoardNode>, Integer>(); 12 int xB = board.length; 13 int yB = board[0].length; 14 if(xB == 1 || yB == 1) 15 return; 16 boolean[][] flag = new boolean[xB][yB]; 17 for(int i=0;i<xB;i++) 18 for(int j=0;j<yB;j++) 19 flag[i][j] = true; 20 for(int i=0;i<xB;i++) 21 { 22 for(int j=0;j<yB;j++){ 23 if(board[i][j]==‘O‘ && flag[i][j]) 24 { 25 //a new group 26 LinkedList<BoardNode> tree = new LinkedList<BoardNode>(); 27 //the corresponding value of the group 28 int value = 1; 29 if(i==0 || i==xB-1 || j==0 || j==yB-1) 30 value = 0; 31 //bread first search for the group 32 tree.offer(new BoardNode(i,j)); 33 flag[i][j] = false; 34 int point = 0; 35 while(point<tree.size()){ 36 BoardNode temp = tree.get(point++); 37 //left neighbor 38 if(temp.y+1==yB-1 && board[temp.x][temp.y+1]== ‘O‘) 39 value = 0; 40 if(temp.y+1<yB && flag[temp.x][temp.y+1] && board[temp.x][temp.y+1]== ‘O‘) 41 { 42 flag[temp.x][temp.y+1] = false; 43 tree.offer(new BoardNode(temp.x,temp.y+1)); 44 } 45 //down neighbor 46 if(temp.x+1 == xB-1 && board[temp.x+1][temp.y] == ‘O‘) 47 value = 0; 48 if(temp.x+1<xB && flag[temp.x+1][temp.y] && board[temp.x+1][temp.y] == ‘O‘) 49 { 50 flag[temp.x+1][temp.y]=false; 51 tree.offer(new BoardNode(temp.x+1,temp.y)); 52 } 53 //up neighbor 54 if(temp.x-1 == 0 && board[temp.x-1][temp.y]==‘O‘) 55 value = 0; 56 if(temp.x-1>=0 && flag[temp.x-1][temp.y] && board[temp.x-1][temp.y] == ‘O‘){ 57 flag[temp.x-1][temp.y]=false; 58 tree.offer(new BoardNode(temp.x-1,temp.y)); 59 } 60 //left neighbor 61 if(temp.y-1==0 && board[temp.x][temp.y-1]==‘O‘) 62 value = 0; 63 if(temp.y-1>=0 && flag[temp.x][temp.y-1] && board[temp.x][temp.y-1]==‘O‘) 64 { 65 flag[temp.x][temp.y-1] = false; 66 tree.offer(new BoardNode(temp.x,temp.y-1)); 67 } 68 } 69 groups.put(tree, value); 70 } 71 } 72 } 73 //flipping the region surrounded by ‘X‘ 74 for(Entry<LinkedList<BoardNode>,Integer> e: groups.entrySet()) 75 { 76 if(e.getValue() == 1) 77 { 78 for(BoardNode bn : e.getKey()) 79 board[bn.x][bn.y] = ‘X‘; 80 } 81 } 82 }
LeetCode OJ - Surrounded Regions,布布扣,bubuko.com
LeetCode OJ - Surrounded Regions
原文:http://www.cnblogs.com/echoht/p/3694569.html