I am using adjacency list representation.
basically
A:[B,C,D] means A is connected to B,C and D
now I am trying to add a method (in python) to add edge in graph.
But before I add an edge. I want to check whether two edges are connected or not.
So for example I want to add an edge between two nodes D and A ( ignorant of the fact taht A and D are connected).
So, since there is no key “D” in the hash/dictionary, it will return false.
Now, very naively, I can check for D and A and then A and D as well.. but thats very scruff.
Or whenever I connect two nodes, I can always duplicate..
I.e when connecting A and E.. A:[E] create E:[A]
but this is not very space efficient.
Basically I want to make this graph direction independent.
Is there any data structure that can help me solve this.
I am hoping that my question makes sense.
For an undirected graph you could use a simple edge list in which you store all the pairs of edges. This will save space and worsen performance but you should know that you can’t have both at the same time so you always have to decide for a tradeoff.
Otherwise you could use a triangular adjacency matrix but, to avoid wasting half of the space, you will have to store it in a particular way (by developing an efficient way to retrieve edge existence without wasting space). Are you sure it is worth it and it’s not just premature optimization?
Adjacency lists are mostly fine, even if you have to store every undirected edge twice, how big is your graph?
Take a look at this my answer: Graph representation benchmarking, so you can choose which one you prefer.