zhincra

1173

Iiw永不言弃
Zaku_Yu
15153661047
navystar
huangbq
Shuheng
qczhang2022str
Theliars
Richard_H

Expelliarmus2011

Andy2035
1024M
Never_79
openallzzz

zhincra
21小时前
incra你向你的女神学习以下吧

zhincra
1天前

zhincra
2天前

zhincra
2天前

zhincra
2天前

zhincra
2天前

zhincra
2天前

zhincra
3天前

zhincra
3天前

Python 代码实现：

python
import queue

# 计算一个数的各个数字之和
def getSum(num):
s = 0
while num > 0:
s += num % 10
num //= 10
return s

def movingCount(k: int, m: int, n: int) -> int:
visited = set()     # 存储访问过的坐标
q = queue.Queue()   # 队列保存待访问的坐标
q.put((0, 0))       # 将起点添加到队列中

cnt = 1             # 统计可以到达的格子数，起点已经访问过了
dx = [0, 1, 0, -1]  # 横向移动的方向数组
dy = [1, 0, -1, 0]  # 纵向移动的方向数组

while not q.empty():
x, y = q.get()
for i in range(4):
newx, newy = x + dx[i], y + dy[i]
if 0 <= newx < m and 0 <= newy < n and (newx, newy) not in visited and getSum(newx) + getSum(newy) <= k:
q.put((newx, newy))
cnt += 1

return cnt


zhincra
4天前
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
if not inorder: return None   # 如果中序遍历为空，则返回空节点

root_val = preorder.pop(0)      # 用 pop 方法弹出前序遍历的第一个节点；
root = TreeNode(root_val)       # 对根节点实例化，并初始化值；

idx = inorder.index(root_val)     # 在中序遍历列表中查找根节点，得到下标位置；

# 递归构建左右子树及其关系；
root.left = self.buildTree(preorder, inorder[:idx])
root.right = self.buildTree(preorder, inorder[idx+1:])

return root    # 返回构建好的二叉树。