DFS基礎
深度優先搜索(Depth First Search)是一種搜索思路,相比廣度優先搜索(BFS),DFS對每一個分枝路徑深入到不能再深入為止,其應用於樹/圖的遍歷、嵌套關系處理、回溯等,可以用遞歸、堆棧(stack)實現DFS過程。
關於廣度優先搜索(BFS)詳見:算法與數據結構基礎 - 廣度優先搜索(BFS)
關於遞歸(Recursion)詳見:算法與數據結構基礎 - 遞歸(Recursion)
樹的遍歷
DFS常用於二叉樹的遍歷,關於二叉樹詳見:
算法與數據結構基礎 - 二叉查找樹(Binary Search Tree)
相關LeetCode題:
559. Maximum Depth of N-ary Tree 題解
897. Increasing Order Search Tree 題解
108. Convert Sorted Array to Binary Search Tree 題解
111. Minimum Depth of Binary Tree 題解
979. Distribute Coins in Binary Tree 題解
366. Find Leaves of Binary Tree 題解
1123. Lowest Common Ancestor of Deepest Leaves 題解
1110. Delete Nodes And Return Forest 題解
1026. Maximum Difference Between Node and Ancestor 題解
515. Find Largest Value in Each Tree Row 題解
199. Binary Tree Right Side View 題解
1145. Binary Tree Coloring Game 題解
863. All Nodes Distance K in Binary Tree 題解
114. Flatten Binary Tree to Linked List 題解
971. Flip Binary Tree To Match Preorder Traversal 題解
105. Construct Binary Tree from Preorder and Inorder Traversal 題解
109. Convert Sorted List to Binary Search Tree 題解
116. Populating Next Right Pointers in Each Node 題解
124. Binary Tree Maximum Path Sum 題解
99. Recover Binary Search Tree 題解
圖的遍歷
樹可視作一類特殊的圖,更一般地DFS用於圖的遍歷,可視化過程
關於圖詳見:算法與數據結構基礎 - 圖(Graph)
相關LeetCode題:
756. Pyramid Transition Matrix 題解
694. Number of Distinct Islands 題解
711. Number of Distinct Islands II 題解
802. Find Eventual Safe States 題解
329. Longest Increasing Path in a Matrix 題解
834. Sum of Distances in Tree 題解
嵌套關系處理
DFS可用於形如 "3[a2[c]]" 存在嵌套關系的問題處理,例如 LeetCode題目394. Decode String:
// 394. Decode String string decode(string s,int& pos){ string res=""; int num=0; for(;pos<s.length();pos++){ if(s[pos]=='['){ string tmp=decode(s,++pos); for(;num>0;num--) res+=tmp; } else if(s[pos]>='0'&&s[pos]<='9') num=num*10+s[pos]-'0'; else if(s[pos]==']') return res; else res+=s[pos]; } return res; }
以上通過DFS進入到最內層的 '[ ]',之后隨着函數返回、由內向外層層展開。
相關LeetCode題:
339. Nested List Weight Sum 題解
DFS與回溯
回溯(Backtracking)算法中選擇一條路徑並走到底的思路,正是DFS。DFS是構成回溯算法的一部分。
關於回溯詳見:算法與數據結構基礎 - 回溯(Backtracking)
相關LeetCode題:
301. Remove Invalid Parentheses 題解
DFS與Memorization
和BFS過程一樣,應用DFS時也有可能重復訪問同一節點,這時可用Memorization記錄哪些節點已經訪問過,避免路徑重復遍歷。
相關LeetCode題:
1059. All Paths from Source Lead to Destination 題解