Skip to content

Instantly share code, notes, and snippets.

@rringler
Created August 11, 2018 06:06
Show Gist options
  • Save rringler/cc7fd9a5952f08a4296499f0cc1f2265 to your computer and use it in GitHub Desktop.
Save rringler/cc7fd9a5952f08a4296499f0cc1f2265 to your computer and use it in GitHub Desktop.
require 'tsort'
class UndirectedGraph < Hash
include TSort
def initialize(size, edges)
super().tap do |hash|
(1..size).each { |i| hash[i] = [] }
edges.each do |(a, b)|
hash[a] << b
hash[b] << a
end
end
end
alias_method :tsort_each_node, :each_key
def tsort_each_child(node, &block)
fetch(node).each(&block)
end
end
UndirectedGraph.new(4, [[1, 2], [1, 3]]).strongly_connected_components
# => [[1, 2, 3], [4]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment