Well, your logic is correct in theory but in practice, you can make your life easier by using two facts which you already know.
First thing, self edge B[i,i], don’t add it to adjacency list…
just as you are taking input, add a simple check
if src == dest vertex
if(val != 0)ans = “no”;
No need to check even for cycles in this case…
Second thing, whenever you input an edge from src vertex to dest vertex, check if there already exist an edge from dest to src vetrex.
If val1 != val2 ans = “no”, no need to check for odd cycles.
else do nothing… don’t even add this edge to graph.
add an undirected edge from src to dest in graph with edge weight val.
Now, all the corner cases we have already covered.
Now, run a dfs on graph, coloring vertex, with same color if edge weight between them is 0.
If edge weight is different, color with opposite color…
If 2-coloring not possible ans = “no”
else ans = “yes”…
You may have a look at my code Here
I have also added a similar explanation Here
Please upvote if you find this helpful…