leetcode [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.
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
Explanation:
Surrounded regions shouldn’t be on the border, which means that any 'O'
on the border of the board are not flipped to 'X'
. Any 'O'
that is not on the border and it is not connected to an 'O'
on the border will be flipped to 'X'
. Two cells are connected if they are adjacent cells connected horizontally or vertically.
题目大意:
一个二维数组中含有O和X两个字母,将被X包围的O变成X,边缘上和边缘相连接的O不能变为X。
解法:
1.将边缘和边缘相连接的O变为#,采用dfs
2.将数组中的O变为X
3.将数组中的#变为O
例如;
X X X X X X X X X X X X
X X O X -> X X O X -> X X X X
X O X X X # X X X O X X
X O X X X # X X X O X X
Java:
class Solution { void dfs(char[][] board,int i,int j){ board[i][j]='#'; int m=board.length,n=board[0].length; if(i+1<m && board[i+1][j]=='O') dfs(board,i+1,j); if(j+1<n && board[i][j+1]=='O') dfs(board,i,j+1); if(i-1>=0 && board[i-1][j]=='O') dfs(board,i-1,j); if(j-1>=0 && board[i][j-1]=='O') dfs(board,i,j-1); } public void solve(char[][] board) { if(board.length==0 || board[0].length==0) return; int m=board.length,n=board[0].length; for(int i=0;i<n;i++){ if(board[0][i]=='O') dfs(board,0,i); if(board[m-1][i]=='O') dfs(board,m-1,i); } for(int i=0;i<m;i++){ if(board[i][0]=='O') dfs(board,i,0); if(board[i][n-1]=='O') dfs(board,i,n-1); } for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(board[i][j]=='O') board[i][j]='X'; } } for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(board[i][j]=='#') board[i][j]='O'; } } } }