簡體   English   中英

使用給定的數據結構查找從節點 A 到節點 B 的路徑

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM