Skip to content

Instantly share code, notes, and snippets.

@saadbinakhlaq
Created February 12, 2022 10:07
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 saadbinakhlaq/3fdb2b5fa9f83c81d8a3c4e13d8f0abc to your computer and use it in GitHub Desktop.
Save saadbinakhlaq/3fdb2b5fa9f83c81d8a3c4e13d8f0abc to your computer and use it in GitHub Desktop.
=begin
Write a function, connected_components_count, that takes in the adjacency list of an undirected graph.
The function should return the number of connected components within the graph.
=end
# 1 - 2
# 4
# |
# 5 -- 6 -- 8
# |
# 7
# 3
graph = {
3 => [],
4 => [6],
6 => [4, 5, 7, 8],
8 => [6],
7 => [6],
5 => [6],
1 => [2],
2 => [1]
}
def explore(graph, current, visited)
return false if visited.include?(current)
visited << current
graph[current].each do |neighbor|
explore(graph, neighbor, visited)
end
true
end
def connected_components_count(graph)
count = 0
visited = Set.new
graph.keys.each do |node|
if explore(graph, node, visited) == true
count += 1
end
end
count
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment