Skip to content

Instantly share code, notes, and snippets.

@iamSahdeep
Created March 4, 2022 20:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamSahdeep/61508015bc854c187bed293e76a2b343 to your computer and use it in GitHub Desktop.
Save iamSahdeep/61508015bc854c187bed293e76a2b343 to your computer and use it in GitHub Desktop.
Dart implementation of counting the number of components in the graph and finding the size of the largest component in it.
/// find the number of connected components within the undirected graph.
/// Component is independent or individual graph within the graph-network
/// Also getting the size of the largest component in it.
const graph = {
0: [8, 1, 5],
1: [0],
5: [0, 8],
8: [0, 5],
2: [3, 4],
3: [2, 4],
4: [3, 2]
};
void main() {
print("Number of components <-> Largest component size : " + getComponents().toString());
}
final visited = <int>{};
String getComponents() {
int largest = 0;
int last = 0;
int components = 0;
for (final key in graph.keys) {
components += helper(key);
if(largest < visited.length - last){
largest = visited.length - last;
}
last = visited.length;
}
return (components.toString() + " <-> " + largest.toString());
}
int helper(int key) {
if (visited.contains(key)) {
return 0;
}
visited.add(key);
for (final neighbor in graph[key]!) {
helper(neighbor);
}
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment