Skip to content

Instantly share code, notes, and snippets.

@canozel
Created December 20, 2016 00:11
Show Gist options
  • Save canozel/6ebc2c7c76a08d084881c6d64edd0966 to your computer and use it in GitHub Desktop.
Save canozel/6ebc2c7c76a08d084881c6d64edd0966 to your computer and use it in GitHub Desktop.
Travelling salesman problem
@graph = { "A" => "BDFH", "B" => "ACRJI", "C" => "BDQR", "D" => "AEPQC", "E" => "DFNP",
"F" => "AENMG","G" => "FLMH", "H" => "AGLKI", "I" => "HKJB", "J" => "IB",
"K" => "IH", "L" => "HG", "M" => "GF", "N" => "FE", "P" => "ED",
"Q" => "DC", "R" => "CB" }
@counter = 0
@path = []
def find_paths(city, last_city)
# Gelen şehri listeye ekliyor
@path << city
# Şehir, son şehirse yolu gösteriyor.
if city == last_city
@counter += 1
puts "PathNo:#{@counter} #{@path.join(" --> ")}"
## Son gelen şehri silip önceki şehire dönüyor.
@path.pop
return @path
end
# Şehirler içerisinde arama yapıp, o şehre ait komşuları sırayla çağırmak
# için döngüye alıyor.
@graph[city].split("").each do |neighbour|
# Oluşturulan yol listesinde daha önce yoksa fonsiyon
# tekrar çağırılır.
if !@path.include?(neighbour)
find_paths(neighbour, last_city)
end
end
# Döngü biterse geri dönebilmesi için
@path.pop
end
find_paths("G", "M")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment