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))
Numerous solution is available online.But I am new to recursion. I want to understand why is my function returning none as the knowledge is going to help me later :) Thanks in advance.
Seems it's returning None since you don't have a return ...
anywhere in your code. I'd make sure that you're explicitly returning where you need to be. For example, two spots that you might want to add a return statement:
return dfs(nei,c^1)
in your dfs()
function as well as:
return dfs(node)
in your possibleBipartition()
function.
Note that you need to explicitly specify the return in Python if there is one unlike in languages like Racket and Haskell.