Question :
In an undirected graph G, two vertices u and v are connected if G contains a path from u to v. An undirected graph is said to be connected if every pair of vertices in the graph are connected. Given an undirected graph, determine whether the graph is connected or not.
Input:
The first line consists of ‘t’, the number of test cases. The first line of each test case consists of ‘v’ and ‘e’, the number of vertices and the number of edges respectively. Next ‘e’ lines consists of ‘a’ & ‘b’ meaning that there is an edge between vertices ‘a’ and ‘b’.
Output:
Print “YES”(without quotes) if the graph is connected and “NO”(without quotes) otherwise
My code:
t=int(input()) #test cases
L=[]
for w in range(t):
v,e=list(map(int,input().split())) #v : vertex , e: edge
l=[[] for n in range(1,v+1)] #adj. list
for j in range(e): #taking the edges and filling l
a,b=list(map(int,input().split())) #edge between a and b
a-=1
b-=1
l[a]+=[b]
l[b]+=[a]
vis=[] #visited
q=[0,] #queue
while q!=[]:
x=q.pop(0) #top element of the queue
if x not in vis: #bfs
vis+=[x]
#print(x,q)
for h in l[x]:
if h not in vis:
vis+=[h]
q+=l[h]
#print(q)
if len(vis)==v: #graph is connected
L+=['YES']
else: #graph is not connected
L+=['NO']
for i in L:print(i)
My doubt:
this works for graphs with cycles, without cycles, and graphs that are not connected. please help by telling any test case that would not give the correct output or what is the error in the above code.
Thank you