saurabh2k26:
As you can see from McA's and my code examples, there are plenty of ways to represent the data structures. For the code McA presented, you can check if a node exists via if (exists $vertices{$node}) { ... } and edges with if (exists $edges{$src}{$dst}) { ... }. In my example, I opted to use a two-level hash, where the first key is the source node and the second key is the destination. So in mine you'd test whether a node exists the same way as McA presented, but to check for the edge, you need to use if (exists $G{$src} and exists $G{$src}{$dst}) { ... }. (You can omit the first clause if you know that the source node exists, but if you're not certain, you need the first clause so that you don't accidentally create (through autovivification) new graph nodes. For example, if you add this line just before the print statement in my code:
print "BAM!\n" if exists $G{25}{30};
You'll find that node 25 gets added to your graph:
{
1 => { 2 => 0, 3 => 0 },
2 => { 3 => 0, 4 => 0 },
3 => { 5 => 0 },
4 => { 5 => 0 },
5 => {},
25 => {},
}
Start: 1, End: 5
Update: If I were going to store any significant data in the nodes, then I'd make it a three-level hash, where the second level would be {EDGES} to let you represent the graph structure, and other keys would hold the node-specific data. The data elements under the {EDGES} can hold edge-specific data, like so:
my %G = (
1=>{ EDGES=> { # Edges for node 1
2=>{ "Data for edge 1->2" },
3=>{ "Data for edge 1->3" },
FOO=> { "a data element for node 1" },
BAR=> { "another data elemment for node 1" },
},
2=> ...
}
If you use McA's method, you can just use the two hashes to hold the data, instead of adding a hash key layer.
...roboticus
When your only tool is a hammer, all problems look like your thumb. |