【发布时间】:2020-05-29 20:11:23
【问题描述】:
import collections
class Solution(object):
def possibleBipartition(self, N, dislikes):
graph = collections.defaultdict(list)
for u, v in dislikes:
graph[u].append(v)
graph[v].append(u)
color = {}
def dfs(node, c = 0):
if node in color:
return color[node] == c
color[node] = c
for nei in graph[node]:
dfs(nei,c^1)
for node in range(1, N+1):
if node not in color:
dfs(node)
g=Solution()
N=3
dislikes=[[1,2],[2,3]]
print(g.possibleBipartition(N, dislikes))
网上有很多解决方案。但我是递归新手。我想了解为什么我的函数不返回任何内容,因为这些知识稍后会帮助我:) 提前致谢。
【问题讨论】:
-
你能确保格式化你的代码,使缩进在正确的位置吗?上面的代码不适合我。
-
@MLavrentyev 完成。我是新手,但我一定会在再次发布之前检查这些内容。
-
别担心!感谢您清理它
标签: python recursion graph depth-first-search