130. Surrounded Regions
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.
For example,
X X X X X O O X X X O X X O X X
After running your function, the board should be:
X X X X X X X X X X X X X O X X
DFS的时候用两个list存访问过的地址,如果没有touch过边界,则用这两个list的值来给board改写。但是这个耗费的space比较大,过不了OJ的大的test case。
public void Solve(char[,] board) { int row = board.GetLength(0); int col = board.GetLength(1); bool[,] visited = new bool[row,col]; for(int i =0;i< row;i++) { for(int j =0;j<col;j++) { if(board[i,j] == 'O' && !visited[i,j]) { List<int> rowStore = new List<int>(); List<int> colStore = new List<int>(); bool NotWrap= BackTracking(board,i,j,row,col,visited,rowStore,colStore); if(!NotWrap) { for(int m = 0;m< rowStore.Count();m++) { board[rowStore[m],colStore[m]] ='X'; } } } } } return; } private bool BackTracking(char[,] board, int x, int y, int row, int col, bool[,] visited, List<int> rowStore, List<int> colStore) { if(x<0 || x> row-1) return true; if(y<0 || y> col-1) return true; if(visited[x,y]) return false; if(x == 0 || x == row-1) { visited[x,y] = true; if(board[x,y] == 'O') return true; } if(y == 0 || y == col-1) { visited[x,y] = true; if(board[x,y] == 'O') return true; } if(board[x,y] == 'X') return false; visited[x,y] = true; rowStore.Add(x); colStore.Add(y); return BackTracking(board,x+1,y,row,col,visited,rowStore,colStore) || BackTracking(board,x-1,y,row,col,visited,rowStore,colStore) || BackTracking(board,x,y+1,row,col,visited,rowStore,colStore) || BackTracking(board,x,y-1,row,col,visited,rowStore,colStore); }
用边界点为‘O’的开始做DFS, 找到的做标记‘#’。然后第二次遍历,标记为‘#’的全换位‘O’, 标记为‘O’的换位‘X’.
public void Solve(char[,] board) { int row = board.GetLength(0); int col = board.GetLength(1); for(int i =0;i< row;i++) { for(int j =0;j<col;j++) { if(((i== 0 || i== row-1) ||(j == 0|| j ==col-1))&&(board[i,j] == 'O')) { BackTracking(board,i,j,row,col); } } } for(int i =0;i< row;i++) { for(int j =0;j<col;j++) { if(board[i,j] == 'O') board[i,j] = 'X'; else if(board[i,j] == '#') board[i,j] = 'O'; } } return; } private void BackTracking(char[,] board, int x, int y, int row, int col) { //if(board[x,y] != 'O') return ; board[x,y] ='#'; if(x<row-1 && board[x+1,y]=='O') BackTracking(board,x+1,y,row,col); if(x>0 && board[x-1,y]=='O') BackTracking(board,x-1,y,row,col); if(y<col-1 && board[x,y+1]=='O') BackTracking(board,x,y+1,row,col); if(y>0 && board[x,y-1]=='O') BackTracking(board,x,y-1,row,col); }