[英]Finding paths from node A to node B using the given data structure
我遇到了一個棘手的問題,因為我無法以遞歸方式思考以找到解決方案。
這是我的數據結構:-
public class Airport {
String name;
Set<Neighbour> neighbours;
...
}
public class Neighbour {
Airport airport;
double costToReach;
...
}
我正在嘗試獲取從一個Airport
到另一個Airport
的可用路徑(列表列表)。
List<List<Airport>> getPaths(Airport source, Airport destination) {
// Logic goes here
}
預期輸入樣本:-
Source airport - Mumbai
Destination airport - Delhi
預期輸出樣本:-
Mumbai -> Pune -> Delhi
Mumbai -> Ahmedabad -> Noida -> Delhi
任何幫助將非常感激。 謝謝!
您可以做的是創建一個方法,該方法需要一個起點、一個目標點和一組已經訪問過的機場。 在此方法中,您可以:
如果您這樣做,您可以有效地嘗試從給定起點到給定目標點的每條路徑,而無需兩次訪問同一機場。 我將把這個遞歸方法的返回值留給你作為練習(必須使用返回值來獲取找到的成功路徑)。
這是 Python 中的解決方案,因為我不精通 Java; 但既然你用“算法”標記了這個問題,我認為可以很容易地理解和轉換。
def getPaths(source, destination):
# We’ve reached the destination
if source["name"] == destination["name"]:
# Return a list of lists
return [[destination["name"]]]
result = []
# If there are no neighbours or
# none of them yield a destination,
# ‘result’ will be an empty list
for neighbour in source["neighbours"]:
paths = getPaths(neighbour, destination)
result.extend([[source["name"]] + path for path in paths])
return result
例子:
mumbai = {"name": "Mumbai"}
pune = {"name": "Pune"}
delhi = {"name": "Delhi"}
ahmedabad = {"name": "Ahmedabad"}
noida = {"name": "Noida"}
# Assign neighbours
mumbai["neighbours"] = [pune, ahmedabad]
pune["neighbours"] = [delhi]
delhi["neighbours"] = []
ahmedabad["neighbours"] = [noida]
noida["neighbours"] = [delhi]
print(getPaths(mumbai, delhi))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.