Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add connected_components_vec #548

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

tesfabpel
Copy link

I've tried petgraph for a little comparison of my C++ code and I noticed that the connected_components algorithm returns only the number of those components without having a way to access the items of such components.
Another problem is that the labels variable has gaps between the elements (eg. in my test it contained [0, 0, 0, 3, 3, 3]) so just returning it as is isn't feasible.
Since it seemed a fairly easy task, I decided to implement it myself.

This new function returns the connected components of the graph similar to boost's connected_components: docs, usage.

The common code has been split in a new private function connected_components_inner.

I'm not really happy about using HashMap here, hopefully performance isn't too bad in real use cases...
Maybe it can be improved in the future, if needed?

From the tests I've done, I also assumed that the labels variable returns a Vec mapping each node to its assigned components such that each position of labels maps to the node's index (ie. labels[i] <-> nodes[i]).

Let me know if the quality of the PR is subpar or just not needed.
Thank you!

TODO

  • Are labels' indices referring to nodes (ie. labels[i] <-> nodes[i])?
  • Choose a better name?

EXAMPLE USAGE

let mut graph : Graph<(), (), Directed> = Graph::new();
let a = graph.add_node(()); // node with no weight
let b = graph.add_node(());
let c = graph.add_node(());
let d = graph.add_node(());
let e = graph.add_node(());
let f = graph.add_node(());
let g = graph.add_node(());
let h = graph.add_node(());

graph.extend_with_edges(&[
     (a, b),
     (b, c),
     (c, d),
     (d, a),
     (e, f),
     (f, g),
     (g, h),
     (h, e)
]);

let components = connected_components_vec(&graph);
// (2, [0, 0, 0, 0, 1, 1, 1, 1]);

This function returns the connected components of the graph similar to boost's connected_components.
The common code has been split in a new private function connected_components_inner.
@tesfabpel tesfabpel force-pushed the feature/connected-components-vec branch from f98d74f to 6f1cd79 Compare March 29, 2023 19:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant