Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม

Yen's k-Shortest Path Algorithm ในโครงสร้างข้อมูล


Yen's k-Shortest Path Algorithm

แทนที่จะให้ Single Shortest Path เดียว Yen's Algorithm ให้ k Shortest Paths เพื่อให้ได้ 2nd, 3rd, ... Shortest Paths

สถานการณ์ตัวอย่าง

เดินทางจาก A ไป B มีหลายเส้นทาง ต้องการ Shortest Path และข้ามเส้นทางที่น้อยกว่าในแง่ Time Complexity

Yen s k-Shortest Path Algorithm ในโครงสร้างข้อมูล

สะพานมียอด B จาก A ไป C ไม่มีใครขึ้นยอด B เส้นทางตรง A→C ยาวกว่า มีหลายวิธีหา Shortest Path แต่ต้องหา Shortest Path ถึง (k-1)

อัลกอริทึม (Cypher/Neo4j)

query = """ MATCH(start: place{id:source}),*end: Place {Id:destination}) 
Call algo.kshortestPaths.stream(start,end,10, "distance") 
Yield nodeIDs, path costs, index 
Return index, [node in algo.getNodeByID(nodeId[1..-1]) | node.id] as path,
Reduce(acc=0.0, cost in costs | acc+cost) as total_cost """
params = {"source": "Alex", "Destination": "US"}
With driver.session() as session:
    rows = session.run(query, params)
    df = pd.DataFrame([dict(record) for record in rows])
    pd.set_option('max_colwidth', 100)
    display(df)