Leetcode刷题(23) BFS系列
102. 二叉树的层序遍历
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import collections
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
levels = []
level = 0
queue = collections.deque([])
queue.append(root)
while(len(queue) > 0):
qsize = len(queue)
levels.append([])
for i in range(qsize):
cur = queue.popleft()
levels[level].append(cur.val)
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
level += 1
return levels
773. 滑动谜题
该为python的实现方式,主要参考labuladong的益智游戏克星:BFS暴力搜索算法
import collections
import copy
class Solution(object):
def slidingPuzzle(self, board):
"""
:type board: List[List[int]]
:rtype: int
"""
# 将二维的数组转化为字符串便于比较
target = "123450"
start = board[0] + board[1]
neighbor = [
[1, 3],
[0, 4, 2],
[1, 5],
[0, 4],
[3, 1, 5],
[4, 2],
]
step = 0
q = collections.deque([])
q.append(start)
visited = [start]
while(len(q) > 0):
qsize = len(q)
for j in range(qsize):
cur = q.popleft()
if "".join(map(str, cur)) == target:
return step
# 找到0的位置
position = 0
for i, c in enumerate(cur):
if c == 0:
position = i
break
for d in neighbor[position]:
new_s = copy.copy(cur)
tmp = new_s[position]
new_s[position] = new_s[d]
new_s[d] = tmp
if new_s in visited:
continue
visited.append(new_s)
q.append(new_s)
step += 1
return -1
111. 二叉树的最小深度
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import collections
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
q = collections.deque([])
if root == None:
return 0
depth = 1
q.append(root)
while(len(q) > 0):
qsize = len(q)
for i in range(qsize):
cur = q.popleft()
if cur.left == None and cur.right == None:
return depth
if cur.left is not None:
q.append(cur.left)
if cur.right is not None:
q.append(cur.right)
depth += 1
return depth
752. 打开转盘锁
import collections
class Solution(object):
def up(self, i, cur):
if cur[i] == '9':
# 先将cur转成list才能修改其中的值
cur = list(cur)
cur[i] = '0'
# 再将list转成string
cur = ''.join(cur)
else:
# 先将cur转成list才能修改其中的值
cur = list(cur)
cur[i] = str(int(cur[i]) + 1)
# 再将list转成string
cur = ''.join(cur)
return cur
def down(self, i, cur):
if cur[i] == '0':
# 先将cur转成list才能修改其中的值
cur = list(cur)
cur[i] = '9'
# 再将list转成string
cur = ''.join(cur)
else:
# 先将cur转成list才能修改其中的值
cur = list(cur)
cur[i] = str(int(cur[i]) - 1)
# 再将list转成string
cur = ''.join(cur)
return cur
def openLock(self, deadends, target):
"""
:type deadends: List[str]
:type target: str
:rtype: int
"""
step = 0
# 记录死亡密码
deadends_dict = dict()
for dead_code in deadends:
deadends_dict[dead_code] = 1
# 建立遍历deque
queue = deque()
queue.append("0000")
# 建立已访问字典
visited = dict()
visited["0000"] = 1
while(len(queue) > 0):
# 得到当前层的节点个数
qsize = len(queue)
for j in range(qsize):
cur = queue.popleft()
if cur == target:
return step
if cur in deadends_dict:
continue
# 将cur的8个邻接节点放入queue
# 密码有4位
for i in range(4):
# 第i+1个数字上波
up_code = self.up(i, cur)
if up_code not in visited.keys():
visited[up_code] = 1
queue.append(up_code)
# 第i+1个数字下波
down_code = self.down(i, cur)
if down_code not in visited.keys():
visited[down_code] = 1
queue.append(down_code)
step += 1
return -1
机器人的运动范围
import collections
class Solution:
def movingCount(self, threshold, rows, cols):
if threshold < 0:
return 0
# write code here
count = 0
track = []
def isVaild(r, c):
r = list(str(r))
c = list(str(c))
total = sum(list(map(int, r + c)))
if threshold < total:
return False
else:
return True
q = collections.deque()
q.append((0, 0))
track.append((0, 0))
while q:
qsize = len(q)
for i in range(qsize):
p = q.popleft()
count += 1
r, c = p
for d in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
nr = r + d[0]
nc = c + d[1]
# 不走回头路
if (nr, nc) in track:
continue
# 不走非法路径
if (nr >= 0 and nr < rows) and (nc >= 0 and nc < cols) and (isVaild(nr, nc)):
q.append((nr, nc))
track.append((nr, nc))
return count