207 课程表
你这个学期必须选修 numCourses 门课程,记为 0 到 numCourses - 1 。
在选修某些课程之前需要一些先修课程。 先修课程按数组 prerequisites 给出,其中 prerequisites[i] = [ai, bi] ,表示如果要学习课程 ai 则 必须 先学习课程 bi 。
例如,先修课程对 [0, 1] 表示:想要学习课程 0 ,你需要先完成课程 1 。
请你判断是否可能完成所有课程的学习?如果可以,返回 true ;否则,返回 false 。
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
# bi 是 ai的前置 bi -> ai
adj = collections.defaultdict(list)
indeg = [0] * numCourses
for p in prerequisites:
a, b = p
adj[b].append(a)
indeg[a] += 1
# 加入0入度的节点
q = []
for i in range(numCourses):
if indeg[i] == 0:
q.append(i)
# main
res = []
while q:
node = q.pop(0)
res.append(node)
for neighbor in adj[node]:
indeg[neighbor] -= 1
if indeg[neighbor] == 0:
q.append(neighbor)
return len(res) == numCourses
399 除法求值
输入:equations = [[“a”,“b”],[“b”,“c”]], values = [2.0,3.0], queries = [[“a”,“c”],[“b”,“a”],[“a”,“e”],[“a”,“a”],[“x”,“x”]]
输出:[6.00000,0.50000,-1.00000,1.00000,-1.00000]
解释:
条件:a / b = 2.0, b / c = 3.0
问题:a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ?
结果:[6.0, 0.5, -1.0, 1.0, -1.0 ]
注意:x 是未定义的 => -1.0
class Solution:
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
graph = defaultdict(list)
for i in range(len(equations)):
x, y = equations[i]
val = values[i]
graph[x].append((y, val))
graph[y].append((x, 1.0 / val))
def bfs(i, j):
if i not in graph or j not in graph:
return -1.0
visited = set()
q = []
q.append([i, 1.0])
while q:
cur_node, cur_val = q.pop(0)
if cur_node == j:
return cur_val
if cur_node in visited:
continue
visited.add(cur_node)
for neibor, val in graph[cur_node]:
q.append([neibor, val * cur_val])
return -1.0
return [bfs(i, g) for i, g in queries]
433 最小基因变化
class Solution:
def minMutation(self, startGene: str, endGene: str, bank: List[str]) -> int:
def isNeighbor(s1, s2):
count = 0
for c1, c2 in zip(s1, s2):
if c1 != c2:
count += 1
if count >= 2:
return False
return True
q = []
q.append(startGene)
visited = set()
res = 0
while q:
l = len(q)
for _ in range(l):
cur = q.pop(0)
if cur == endGene:
return res
if cur in visited:
continue
visited.add(cur)
for neighbor in bank:
if isNeighbor(cur, neighbor):
q.append(neighbor)
res += 1
return -1