DFS outputting 0

whitehousechef·2023년 10월 31일
0

1) check if any variables share the same name. For example, I declared x as the minimum distance from start to end point before dfs function. But in my dfs function, x and y parameters are passed in, where x represents the row. So my condition to break out of loop that checks x actually checks current row, not the min. Distance (x) that I intended.

e.g.

n, m, x = map(int, input().split())
graph = []

for _ in range(n):
    graph.append(list(input().rstrip()))

print(graph)
ans = 0
moves = [[1, 0], [0, 1], [-1, 0], [0, -1]]
visited = [[False for _ in range(m)] for _ in range(n)]

def dfs(x, y, count):
    global ans
    if x == 0 and y == m - 1:
    ## here x is not the variable we want, but it is current row (X)
        if count == x:
            ans += 1
        return

2) check if your starting point is declared as visited = True or graph[x][y]=’’. Even before your dfs (actually you can declare in your dfs but anyway), you should declare your start point as visited. Or else the next dfs loop will traverse back to your start point.

visited[n - 1][0]=True
dfs(n - 1, 0, 1)

3) check if you are actualling calling the dfs function after u implemented it

4) V IMPT
If we pass int values as parameters in our dfs function, the int values will not be updated with dfs search. This applies to both java and python cuz:

integers in python are immutable.

def increment(n):
    n += 1  # This creates a new int object, doesn't affect caller

num = 5
increment(num)
print(num)  # 5, not 6

so if u intend to change a variable along dfs, u should use a mutable object like list or dict

def increment(counter):
    counter[0] += 1

num = [5]
increment(num)
print(num[0])  # 6

see this https://velog.io/@whitehousechef/Leetcode-3373.-Maximize-the-Number-of-Target-Nodes-After-Connecting-Trees-II

0개의 댓글