题目描述(中等难度)
有一点点像围棋,把被x
围起来的o
变成x
,边界的o
一定不会被围起来。如果o
和边界的o
连通起来,那么这些o
就都算作不被围起来,比如下边的例子。
X X X X X
O O O X X
X X X O X
X O X X X
上边的例子就只需要变化1
个o
.
解法一
把相邻的o
看做是联通的图,然后从每一个o
开始做DFS
。
如果遍历完成后没有到达边界的o
,我们就把当前o
改成x
。
如果遍历过程中达到了边界的o
,直接结束DFS
,当前的o
就不用操作。
然后继续考虑下一个o
,继续做一次DFS
。
public class Surrounded_Regions {public void solve(char[][] board){if(board.length==0 || board[0].length==0) return;int m = board.length,n=board[0].length;// start from first and last column,turn 'o' to '*'for(int i = 0;i<m;i++){if(board[i][0]=='o')boundaryDFS(board,i,0);if(board[i][n-1]=='o')boundaryDFS(board,i,n-1);}//start from first and last row,turn 'o' to '*'for(int j=0;j<n;j++){if(board[0][j]=='o')boundaryDFS(board,0,j);if(board[m-1][j]=='o')boundaryDFS(board,m-1,j);}for(int i =0;i<m;i++){for(int j=0;j<n;j++){if(board[i][j]=='o')board[i][j]='x';else if(board[i][j]=='*')board[i][j]='o';}}}private void boundaryDFS(char[][] board,int i,int j){if(i<0 ||j<0 || i>board.length-1 || j>board[0].length-1 || board[i][j]!='o')return;board[i][j]='*';boundaryDFS(board,i+1,j);boundaryDFS(board,i-1,j);boundaryDFS(board,i,j+1);boundaryDFS(board,i,j-1);}
}
参考文献
- https://leetcode.com/problems/surrounded-regions/discuss/41633/Java-DFS-%2B-boundary-cell-turning-solution-simple-and-clean-code-commented.