Initial code was this
from collections import defaultdict, deque
n = int(input())
cons = int(input())
graph = defaultdict(list)
for _ in range(cons):
start,end = map(int,input().split())
graph[start].append(end)
graph[end].append(start)
visited=[False for _ in range(n)]
global ans
ans = 0
def dfs(i,visited,graph):
global ans
visited[i]=True
for node in graph[i]:
if not visited[node]:
dfs(node,visited,graph)
ans +=1
dfs(1,visited,graph)
print(ans)
indexerror
but I got a IndexError
error.
My dfs logic is right but while the input graph that I am getting is not 0-indexed (it starts from node 1 and not node 0), I was wrongly assigning my visited list as 0-indexed of size n. It should be size n+1 to accomodate for 1 more element since it is not 0-indexed.
So fixing
visited=[False for _ in range(n+1)]
made it right