直接看算法吧:
src:
class Solution:def checkWays(self, pairs: List[List[int]]) -> int:adj &#61; defaultdict(set)for x, y in pairs:adj[x].add(y)adj[y].add(x)root &#61; next((node for node, neighbours in adj.items() if len(neighbours) &#61;&#61; len(adj) - 1), -1)if root &#61;&#61; -1:return 0ans &#61; 1for node, neighbours in adj.items():if node &#61;&#61; root:continuecurDegree &#61; len(neighbours)parent &#61; -1parentDegree &#61; maxsizefor neighbour in neighbours:if curDegree <&#61; len(adj[neighbour]) < parentDegree:parent &#61; neighbourparentDegree &#61; len(adj[neighbour])if parent &#61;&#61; -1 or any(neighbour !&#61; parent and neighbour not in adj[parent] for neighbour in neighbours):return 0if parentDegree &#61;&#61; curDegree:ans &#61; 2return ans
总结&#xff1a;
直接模拟
用next取iter中的元素&#xff0c;越超界则返回给定值