Search code examples
pythondepth-first-search

Python def in if True don't return


This code,, if count >= 3 : print("test") success but return True not working.. why..?!?

def dfs(a, b, i, count):
    
    if a<=-1 or a>=7 or b<=-1 or b>=7:
        return False
    
    if lists[a][b] == i and lists[a][b] > 0:
        
        lists[a][b] = -1 #확인 했음을 표시
        count += 1;
        
        dfs(a+1, b, i, count)
        dfs(a-1, b, i, count)
        dfs(a, b+1, i, count)
        dfs(a, b-1, i, count)
        
        if count >= 3 :
            print("test") #THIS PRINT SUCCESS!!
            return True   #BUT DON'T return True!!
        else:
            return False
            
    return False
        

lists = []
for i in range(7):
    lists.append(list(map(int, input().split(" "))))

result = 0

for a in range(0, 7):
    for b in range(0, 7):
        if dfs(a, b, lists[a][b], 0) == True:
            
            #Never run.. this codes..
            print("result up?") 
            result += 1

print( result )

input data is

2 1 5 1 1 3 4
2 1 5 1 3 5 3
2 3 4 5 2 2 4
4 4 3 2 3 1 3
4 3 5 3 1 4 3
5 4 4 3 3 5 5
2 1 3 5 1 1 2

please help me ㅠㅠ..


Solution

  • The problem lies in

            dfs(a+1, b, i, count)
            dfs(a-1, b, i, count)
            dfs(a, b+1, i, count)
            dfs(a, b-1, i, count)
    

    If you change it to

            print(dfs(a+1, b, i, count))
            print(dfs(a-1, b, i, count))
            print(dfs(a, b+1, i, count))
            print(dfs(a, b-1, i, count))
    

    Suddenly the "missing" return true appears. The problem here is that you don't do anything with the actually returned "True". So you need to do something with this returned value, I'm not certain what you're attempting, but I hope it answers the question as to what happened

    Part of the output

    False
    False
    False
    False
    test
    True
    False
    False