1 / 14

DFS & BFS & Backtracking

DFS & BFS & Backtracking. N.S.Lin@ntnu.csie@Taiwan www.csie.ntnu.edu.tw/~u99256. CC – 非商業性 – 相同方式. Preface. DFS : Depth-First-Search BFS : Breadth-First-Search 常用 於圖形問題 後者常用來尋找最佳解. DFS. 沿著一條路走,遇到死路再回頭, 直到 得解或確定無 解 是一種 窮舉的方法 使用 Stack 利用 Recursion. D FS. (4 , 5). (4 , 4).

Download Presentation

DFS & BFS & Backtracking

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. DFS&BFS& Backtracking N.S.Lin@ntnu.csie@Taiwan www.csie.ntnu.edu.tw/~u99256 CC – 非商業性 – 相同方式

  2. Preface • DFS : Depth-First-Search • BFS : Breadth-First-Search • 常用於圖形問題 • 後者常用來尋找最佳解

  3. DFS • 沿著一條路走,遇到死路再回頭, 直到得解或確定無解 • 是一種窮舉的方法 • 使用 Stack • 利用 Recursion

  4. DFS (4 , 5) (4 , 4) (1 , 4) (4 , 3) (2 , 4) (4 , 2) (2 , 2) (4 , 1) (2 , 2) (3 , 1) (2 , 1) (1 , 1)

  5. DFS function DFS( node ) if( got-end ){ print:"I got it!" } if can-go( node.up){ go( node.up) } if can-go( node.right){ go( node.right) } if can-go( node.left){  go( node.right )  } if can-go( node.down){ go( node.down) } end

  6. BFS • 同時嘗試每條路徑 • 是一種擴散的概念 • 使用 Queue • 常用於尋找最佳解

  7. BFS (5 , 1) (4 , 2) (2 , 4) (4 , 1) (2 , 3) (5 , 4) (3 , 1) (4 , 4) (2 , 2) (4 , 3) (2 , 1) (1 , 1) (1 , 4)

  8. Backtracking • 在窮舉的時候多做一些檢查判斷, 避免浪費時間在探尋不可能的路徑上

  9. 8-Queen Problem

  10. 8-Queen Problem • 方法一 -暴力硬做, 每種擺法都試一次 • 8 * 8 棋盤上:64 * 63 * …. * 57(次) • 方法二 – 以 Backtracking 加快速度 • 每一列只擺一隻皇后 • 8* 8 棋盤上:8 * 7 * 6 * 5 * 4 * 3 * 2 * 1(次) • 比較次數減為 1/4426165368 倍

  11. Use C++ STL to easy ur work • Stack : #include <stack> … std::stack<(DATA_TYPE)> stack_1 stack_1.push() stack_1.top() stack_1.pop() stack_1.empty() stack_1.size() C++ Reference : http://www.cplusplus.com/reference/stl/stack/

  12. Use C++ STL to easy ur work • Queue : #include <queue> … std::queue<(DATA_TYPE)> queue_1 queue_1.push() queue_1.front() queue_1.back() queue_1.pop() queue_1.empty() queue_1.size() C++ Reference : http://www.cplusplus.com/reference/stl/queue/

  13. Use C++ STL to easy ur work 執行結果: C++ Reference : http://www.cplusplus.com/reference/stl/queue/

  14. Test Yourself • 10336 - Rank the Languages • 439 - Knight Moves • 750 - 8 Queens Chess Problem • 11352 - Crazy King

More Related