# [Cracking the Coding Interview] 4.1 Route Between Nodes 节点间的路径

Given a directed graph, design an algorithm to find out whether there is a route between nodes.

 1 class Node
2   attr_accessor :name, :neighbors
3
4   def initialize(name)
5     @name = name
6     @neighbors = []
7   end
8 end
9
10 class Graph
11   attr_accessor :nodes
12
13   def initialize
14     @nodes = []
15   end
16 end

BFS Version

class Node
attr_accessor :name, :neighbors, :visited

def initialize(name)
@name = name
@neighbors = []
@visited = false
end
end

def has_route?(node1, node2)
return false if node1.nil? || node2.nil?

q = Queue.new
node1.visited = true
q << node1

while !q.empty?
cur = q.pop

return true if cur.name == node2.name

cur.neighbors.each do |n|
if !n.visited
n.visited = true
q << n
end
end
end
false
end

DFS Version

class Node
attr_accessor :name, :neighbors, :visited

def initialize(name)
@name = name
@neighbors = []
@visited = false
end
end

def has_route?(node1, node2)
return false if node1.nil? || node2.nil?
return true if node1.name == node2.name

node1.visited = true
node1.neighbors.each do |n|
next if n.visited
if has_route?(n, node2)
return true
end
end
false
end

posted @ 2018-06-15 04:36 infinitycoder 阅读(...) 评论(...) 编辑 收藏