130. Surrounded Regions
Posted 咖啡中不塌缩的方糖
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
public void Solve(char[,] board) { if(board.GetLength(0)==0 || board.GetLength(0)==0 ) return; int rowLength = board.GetLength(0); int colLength = board.GetLength(1); for(int i = 0;i<rowLength;i++) { for(int j = 0;j<colLength;j++) { if((i==0||j==0||i == rowLength-1 || j == colLength -1)&&(board[i,j]==‘O‘)) { DFS(board,i,j); } } } for(int i = 0;i<rowLength;i++) { for(int j = 0;j<colLength;j++) { if(board[i,j]==‘T‘) board[i,j]=‘O‘; else if(board[i,j]==‘O‘) board[i,j]=‘X‘; } } return; } private void DFS(char[,] board, int row, int col) { board[row,col] = ‘T‘; if(row>0 && board[row-1,col] == ‘O‘) DFS(board,row-1,col); if(row<(board.GetLength(0)-1) && board[row+1,col] == ‘O‘) DFS(board,row+1,col); if(col>1 && board[row,col-1] == ‘O‘) DFS(board,row,col-1); if(col<(board.GetLength(1)-1) && board[row,col+1] == ‘O‘) DFS(board,row,col+1); }
以上是关于130. Surrounded Regions的主要内容,如果未能解决你的问题,请参考以下文章