130. 被围绕的区域 leetcode
思路:
1. 题意: 将‘O’替换为‘X’ 即 if board[ i ][ j ] == 'O' : board[ i ][ j ] == 'X', 但是一旦该元素与四条边相连就保持‘O’
2. 所以本题只需要先排除与四条边相连的岛屿,题目就转换为刚做的 200.岛屿数量。
3. 先遍历四条边,将边上的岛屿 从'O' 变成 ‘S‘, 此时board中剩下的所有’O‘都是非边’O‘ 直接遍历成’X‘
4. 结束后将边岛屿 ’S‘ 全部遍历成’O‘
收获:
1. 岛屿数量中用的 那个递归太好用了 一定要背下来,亮点有:
1) 赋值在一进入函数的时候,就只需要写一遍; 如果在判断的时候写,就可能写两三处,造成遗漏。
board[x][y] = 'S'
2)将输入的坐标 (x,y) 做成 列表上下左右,会好看一点
dirs = [(x-1,y),(x+1,y),(x,y-1),(x,y+1)]
3)要先判断范围,再判断取值,不然会 out of index
if 0<=r<nr and 0<=c<nc and board[r][c] == 'O': set_to_S(r,c,board)
2. 函数代码:
def set_to_S(x,y,board):
board[x][y] = 'S'
dirs = [(x-1,y),(x+1,y),(x,y-1),(x,y+1)]
nr = len(board)
nc = len(board[0])
for r,c in dirs:
if 0<=r<nr and 0<=c<nc and board[r][c] == 'O':
set_to_S(r,c,board)
代码:
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
def set_to_S(x,y,board):
board[x][y] = 'S'
dirs = [(x-1,y),(x+1,y),(x,y-1),(x,y+1)]
nr = len(board)
nc = len(board[0])
for r,c in dirs:
if 0<=r<nr and 0<=c<nc and board[r][c] == 'O':
set_to_S(r,c,board)
if not board :
return board
nr = len(board)
nc = len(board[0])
if nr<3 or nc<3:
return board
for j in range(nc):
if board[0][j] == 'O':
set_to_S(0,j,board)
if board[nr-1][j] == 'O':
set_to_S(nr-1,j,board)
for i in range(nr):
if board[i][0] == 'O':
set_to_S(i,0,board)
if board[i][nc-1] == 'O':
set_to_S(i,nc-1,board)
for i in range(1,nr-1):
for j in range(1,nc-1):
if board[i][j] == 'O':
board[i][j] = 'X'
for i in range(nr):
for j in range(nc):
if board[i][j] == 'S':
board[i][j] = 'O'
return board