Created
March 4, 2022 20:51
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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