7 Algorithm Design Design Sketch Design SketchCont Pseudo

  • Slides: 8
Download presentation
7. 演算法設計 (Algorithm Design) • Design Sketch:

7. 演算法設計 (Algorithm Design) • Design Sketch:

Design Sketch(Cont. )

Design Sketch(Cont. )

Pseudo code /**find. Shortest. Path * 利用Dijkstra Algorithm 由cities中找出: 從source出發到cities 中各點的shortest path * 若destination

Pseudo code /**find. Shortest. Path * 利用Dijkstra Algorithm 由cities中找出: 從source出發到cities 中各點的shortest path * 若destination != null 且 destination與source之間有最短路徑 * 則回傳destination與source之間的最短路徑 * Time complexity: O(n 3) * * @param destination -Cities 指定的目的地 * * @return Linked. List<Adjacent. Cities> -source到destination的最 短路徑 * */

find. Shortest. Path • 1. 將source加入shortest. Path. List中, 並設定其最短路徑的距離為 0 • Time complexity: O(1)

find. Shortest. Path • 1. 將source加入shortest. Path. List中, 並設定其最短路徑的距離為 0 • Time complexity: O(1) • 2. while shortest. Path. List. size <= cities. Sum, Time complexity: O(n 3) • 1 findshortest. Path. List, 得到所有與shortest. Path. List 相連的 Cities中, 距離最近的city. A 及在city. A到source的最短路徑上, 在 shortest. Path. List中與city A直接相連的city. B • Time Complexity: O(n 2) • 2 檢查是否找到city. A, 若沒有找到, 則回傳 destination的最短路 徑 • 3 將city. A加入shortest. Path. List並設定其最短路徑為 : city. B的最 短路徑 + city. A

/**findshortest. Path. List * 找出cities中與shortest. Path. List相連距離最短的city. A * 以及shortest. Path. List中, 直接與city. A相連的city.

/**findshortest. Path. List * 找出cities中與shortest. Path. List相連距離最短的city. A * 以及shortest. Path. List中, 直接與city. A相連的city. B * Time complexity: O(n 2) * * @param shortest. Path. List - Linked. List<Cities>, 已經找到 shortest path的cities * @param city. A – Adjacent. Cities , 與shortest. Path. List中 的城市相連且距離最短的城市 * @param city. B - Cities, shortest. Path. List 中直接與city. A 相連的城市 * @throws 若距離為負值 */

findshortest. Path. List • while i = 0 to size, Time Complexity: O(n 2)

findshortest. Path. List • while i = 0 to size, Time Complexity: O(n 2) 1. distance = shortest. Path. List[i]的最短路徑長度 2. 從cities中find. City, 找出符合shortest. Path. List[i]. city. Name的城市: finding. City 以及 它與其他城市的連結關係, Time complexity: O(n) 3. while j = 0 to finding. City的Adjacent. Cities. size, Time complexity: O(n) if (finding. City的adjacent. Cities[j]. distance + distance) < (city. A到city. B的距 離 + city. B的最短路徑長度) Then if finding. City的adjacent. Cities[j]不存在於shortest. Path. List Then 1. city. A = finding. City的adjacent. Cities[j] 2. city. B = shortest. Path. List[i]

/**find. City * 從cities中找出符合city. Name的Cities並回傳 * 若沒有符合則回傳null * * @param city. Name –String, 查詢的city.

/**find. City * 從cities中找出符合city. Name的Cities並回傳 * 若沒有符合則回傳null * * @param city. Name –String, 查詢的city. Name * @return –Cities, 符合的Cities */

find. City • while i = 0 to cities. size • if cities[i]. city.

find. City • while i = 0 to cities. size • if cities[i]. city. Name == city. Name • then return cities[i]