I wrote code using some kind of breadth-first-search algorithm in order to find a path (any path!) from a start point to an end point. There are no weights/different distances involved from path-to path-so I am not sure I should use Dijkstra's algorithm.
However, I am required to find a solution that can search for and return a path within a second (while this current code can complete it in five seconds). Assuming my code is inefficient, what can I do better?
$visited = Array.new
$queue = Array.new
def find_path (start, endpoint)
returnArray = Array.new
start = start.to_s
endpoint = endpoint.to_s
$queue.push(start)
nextPaths = get_next_paths(start)
if start == endpoint
return returnArray.push(endpoint)
else
$visited.push(start)
$queue.pop(start.to_i)
nextPaths.each { |i| next if $visited.include?(i);
$queue.push(i)
returnArray = find_path(i.to_i, endpoint.to_i)
if returnArray == nil
next
elsif !returnArray.empty?
returnArray.unshift(start)
return returnArray
end
}
end
if !$queue.empty?
return []
else
return nil
end
end
def get_next_paths(id)
return $h[id.to_s]
end
def direct_connection?(id1, id2)
next_paths = get_next_paths(id1)
return (next_paths!=nil and next_paths.include?(id2.to_s))
end
def valid_path?(path)
while (path.length>1)
current_element = path.first
next_element = path[1]
if (!direct_connection?(current_element, next_element))
return false
end
path.shift
end
return true
end