Last active
August 29, 2015 14:07
-
-
Save matutter/3b8e7a8a58f8cf40723c to your computer and use it in GitHub Desktop.
inside_cyclic.rb given a directed or undirected graph check if given element is in a cyclic structure
This file contains hidden or 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
| =begin | |
| :mat utter, 10/18/2014 | |
| =end | |
| class Graph | |
| def initialize() | |
| @graph = Hash.new(false) | |
| @visit = Hash.new(false) | |
| @target = false | |
| end | |
| def add(key,val) | |
| @visit [key] = false | |
| if @graph.has_key?(key) | |
| @graph[key].push( val ) | |
| else | |
| @graph[key] = Array.new | |
| @graph[key].push( val ) | |
| end | |
| # for directed graphs comment below out | |
| if @graph.has_key?(val) | |
| @graph[val].push( key ) | |
| else | |
| @graph[val] = Array.new | |
| @graph[val].push( key ) | |
| end | |
| @graph[val].uniq! | |
| @graph[key].uniq! | |
| end | |
| def delete(u,v) | |
| @graph[u].delete_if { |x| x == v } | |
| @graph[v].delete_if { |x| x == u } | |
| end | |
| def to_s | |
| return "#{@graph}\n#{@visit}" | |
| end | |
| def Next # gets next unvisited | |
| end | |
| def G | |
| @graph | |
| end | |
| #cycle part | |
| def in_cycle(u,v) | |
| self.delete(u,v) | |
| puts "Goal = #{v}" | |
| @visit[u] = true | |
| return self._check_cycle(u, v) | |
| end | |
| def _check_cycle(u,v) | |
| @graph[u].each do | val | | |
| next if @visit[val] | |
| puts "#{u} -> #{val} " | |
| return true if val == v | |
| @visit[val] = true | |
| return self._check_cycle( val, v ) | |
| end | |
| return false | |
| end | |
| end | |
| g = Graph.new | |
| g.add(:A,:B) | |
| g.add(:A,:E) | |
| g.add(:B,:C) | |
| g.add(:C,:F) | |
| g.add(:C,:D) | |
| g.add(:D,:E) | |
| g.add(:E,:D) | |
| g.add(:D,:B) | |
| # for directed use below for end nodes | |
| #g.add(:F,false) | |
| # this has to actually be an edge of course | |
| u = :F | |
| v = :C | |
| if g.in_cycle(u,v) | |
| puts | |
| puts "\n{#{u},#{v}} found inside cyclic structure\n" | |
| else | |
| puts | |
| puts "\n{#{u},#{v}} is not inside cyclic structure\n" | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment