被围绕的区域
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.
Code(By myself):
class Solution(object):
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
if not board:
return
self.row = len(board)
self.col = len(board[0])
for i in range(1,self.col-1):
if board[0][i] == 'O' and board[1][i] == 'O':
self.change(board,1,i)
if board[self.row-1][i] == 'O' and board[self.row-2][i] == 'O':
self.change(board,self.row-2,i)
for i in range(1,self.row-1):
if board[i][0] == 'O' and board[i][1] == 'O':
self.change(board,i,1)
if board[i][self.col-1] == 'O' and board[i][self.col-2] == 'O':
self.change(board,i,self.col-2)
for i in range(1,self.row-1):
for j in range(1,self.col-1):
if board[i][j] == 'O':
board[i][j] = 'X'
elif board[i][j] == 'W':
board[i][j] = 'O'
def change(self,board,i,j):
board[i][j] = 'W'
if j + 1 < self.col-1 and board[i][j+1] == 'O':
self.change(board,i,j+1)
if i + 1 < self.row - 1 and board[i+1][j] == 'O':
self.change(board,i+1,j)
if i - 1 > 0 and board[i-1][j] == 'O':
self.change(board,i-1,j)
if j - 1 > 0 and board[i][j-1] == 'O':
self.change(board,i,j-1)
Code(others):
class Solution(object):
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
if not any(board):
return
n, m = len(board), len(board[0])
q = [ij for k in range(max(n,m)) for ij in ((0, k), (n-1, k), (k, 0), (k, m-1))]
while q:
i, j = q.pop()
if 0 <= i < n and 0 <= j < m and board[i][j] == 'O':
board[i][j] = 'W'
q += (i, j-1), (i, j+1), (i-1, j), (i+1, j)
board[:] = [['XO'[c == 'W'] for c in row] for row in board]
总结:
从外围向里扩散。
二叉树的最近公共祖先
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4]
Example:
_______3______ / \ ___5__ ___1__ / \ / \ 6 _2 0 8 / \ 7 4
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 Output: 3 Explanation: The LCA of of nodes5
and1
is