这道题目的关键在于反向思路。如果要去判断某个O所在的位置是不是被包围,挺困难的,所以反向去找那些没有被包围的所有O的位置,而题目里明确说了,在四条boundary上的O是不被包围的。这应该是最straight forward的方法了,不过从提交结果来看速度还是比较慢。具体流程如下:
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
def dfs(i,j):
if i<0 or i>=m or j<0 or j>=n or board[i][j]!='O' or (i,j) in visited:
return
pos.append((i,j))
visited.add((i,j))
dfs(i+1,j)
dfs(i-1,j)
dfs(i,j+1)
dfs(i,j-1)
if not len(board) or not len(board[0]):
return
visited = set()
pos = []
m = len(board)
n = len(board[0])
for i in range(m):
dfs(i,0)
dfs(i,n-1)
for i in range(n):
dfs(0,i)
dfs(m-1,i)
for i in range(m):
for j in range(n):
if board[i][j]=='O' and (i,j) not in pos:
board[i][j] = 'X'
C++版本如下:
class Solution {
public:
void solve(vector<vector<char>>& board) {
if (board.empty() || board[0].empty()) return;
set<pair<int,int>> visited;
set<pair<int,int>> pos;
for (int i=0;i<board.size();++i){
dfs(i,0,board,visited,pos);
dfs(i,board[0].size()-1,board,visited,pos);
}
for (int i=0;i<board[0].size();++i){
dfs(0,i,board,visited,pos);
dfs(board.size()-1,i,board,visited,pos);
}
for (int i=0;i<board.size();++i){
for (int j=0;j<board[0].size();++j){
pair<int,int> curr(i,j);
if (board[i][j]=='O' && !pos.count(curr)){
board[i][j] = 'X';
}
}
}
}
void dfs(int i, int j, vector<vector<char>>& board,set<pair<int,int>>& visited,set<pair<int,int>>& pos){
pair<int,int> curr_pos(i,j);
if (i<0||i>=board.size()||j<0||j>=board[0].size()||board[i][j]!='O'||visited.count(curr_pos)) return;
pos.insert(curr_pos);
visited.insert(curr_pos);
dfs(i+1,j,board,visited,pos);
dfs(i-1,j,board,visited,pos);
dfs(i,j+1,board,visited,pos);
dfs(i,j-1,board,visited,pos);
}
};
上面速度比较慢的原因应该在于visited访问的时候需要log(n)的额外复杂度,其实这种问题不需要建立visited,直接通过修改board的状态就可以了,在从边界开始BFS或者DFS的时候,将能访问到的O全部修改为‘#’,最后只需将所有是’#'的位置恢复成O就可以了,我把BFS和DFS两种写法都写在一起了。只是替换不同的部分即可
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
if not len(board):
return
m = len(board)
n = len(board[0])
#q = collections.deque()
q = []
for i in range(m):
if board[i][0] == 'O':
q.append((i,0))
if board[i][n-1] == 'O':
q.append((i,n-1))
for j in range(n):
if board[0][j] == 'O':
q.append((0,j))
if board[m-1][j] == 'O':
q.append((m-1,j))
# while q:
# curr = q.popleft()
# board[curr[0]][curr[1]] = '#'
# dirs = [[1,0],[-1,0],[0,1],[0,-1]]
# for d in dirs:
# x = curr[0]+d[0]
# y = curr[1]+d[1]
# if 0<=x
# if board[x][y] == 'X':
# continue
# if board[x][y] == 'O':
# q.append((x,y))
def helper(i,j):
if i<0 or i>=m or j<0 or j>=n or board[i][j]=='#' or board[i][j]=='X':
return
board[i][j] = '#'
helper(i+1,j)
helper(i-1,j)
helper(i,j+1)
helper(i,j-1)
for (i,j) in q:
helper(i,j)
for i in range(m):
for j in range(n):
if board[i][j] == '#':
board[i][j] = 'O'
else:
board[i][j] = 'X'