主要内容
- DFS搜索
- 链表遍历
扫雷游戏
思路
DFS搜索即可,注意迭代的终止条件有两个:
- 只有方块为'E'的需要进行搜索,其他条件直接终止递归
- 对于'E'方块周围需要统计地雷个数,如果地雷个数大于0个,更新方块,并终止递归
代码
class Solution(object):
def updateBoard(self, board, click):
"""
:type board: List[List[str]]
:type click: List[int]
:rtype: List[List[str]]
"""
def updateBoard(board, height, width):
if board[click[0]][click[1]] == 'M':
board[click[0]][click[1]] = 'X'
else:
dfs(click[0], click[1], height, width)
return board
def dfs(x, y, height, width):
mine_cnt = 0
if board[x][y] != 'E':
return
for i in [x-1, x, x+1]:
for j in [y-1, y, y+1]:
if i == x and j == y:
continue
if i < 0 or i >= height:
continue
if j < 0 or j >= width:
continue
if board[i][j] == 'M':
mine_cnt += 1
if mine_cnt > 0:
board[x][y] = str(mine_cnt)
return
board[x][y] = 'B'
for i in [x-1, x, x+1]:
for j in [y-1, y, y+1]:
if i == x and j == y:
continue
if i < 0 or i >= height:
continue
if j < 0 or j >= width:
continue
dfs(i, j, height, width)
return
height = len(board)
if height <= 0:
return board
width = len(board[0])
if width <= 0:
return board
updateBoard(board, height, width)
return board
两数相加
思路
链表遍历问题,需要注意几点:
- 使用pseudoNode可以规避掉空链表的额外判断
- 两个链表长度不一定一致
- 最后结果可能需要进一位
代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
pseudoNode = ListNode(0)
ptr = pseudoNode
ptr1 = l1
ptr2 = l2
plus = 0
while ptr1 is not None and ptr2 is not None:
result = ptr1.val + ptr2.val + plus
ptr1.val = result%10
plus = result/10
ptr.next = ptr1
ptr1 = ptr1.next
ptr2 = ptr2.next
ptr = ptr.next
tmpPtr = None
if ptr1 is not None:
tmpPtr = ptr1
if ptr2 is not None:
tmpPtr = ptr2
while tmpPtr is not None:
result = tmpPtr.val + plus
tmpPtr.val = result%10
plus = result/10
ptr.next = tmpPtr
tmpPtr = tmpPtr.next
ptr = ptr.next
if plus > 0:
ptr.next = ListNode(plus)
return pseudoNode.next