经过一个月的倦怠期,我徐汉三又回来啦!FLAG每天至少一道题坚持到秋招offer!!!
今天的题目是DFS思想。https://leetcode.com/problems/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’以及和边界上的‘O’相邻的‘O’ 可以保留,其余的转成‘X’.
所以可以从四个边界出发进行深度优先遍历,标记和边界上‘O’相邻的“O”为‘*’;
然后依次遍历所有点,将“*”变成‘O’,其他的都是‘X’.
注意不要忘记边界条件判断。
class Solution {
private int[][] directions = {{0,1},{0,-1},{1,0},{-1,0}};
public void solve(char[][] board) {
if(board==null || board.length==0)
return;
for(int i=0;i<board.length;i++){
dfs(board, i, 0);
dfs(board, i, board[0].length-1);
}
for(int i=0;i<board[0].length;i++){
dfs(board, 0, i);
dfs(board, board.length-1, i);
}
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
if(board[i][j]=='*')
board[i][j]='O';
else
board[i][j]='X';
}
}
}
public void dfs(char[][] board, int i, int j){
if(i<0 || i>= board.length || j<0 || j>=board[0].length || board[i][j]!='O')
return;
board[i][j]='*';
for(int[] dir:directions){
dfs(board, i+dir[0], j+dir[1]);
}
}
}