深度优先搜索(DFS)是一种用于遍历或搜索树或图的算法。它从根节点开始,沿着每个分支尽可能深地搜索,直到无法继续为止,然后回溯到上一个节点,继续搜索其他分支。以下是在不同编程语言中实现深度优先搜索的示例:
Python 示例
```python
def dfs(graph, start, end):
visited = set()
stack = [start]
while stack:
node = stack.pop()
if node not in visited:
visited.add(node)
if node == end:
return True
stack.extend(neighbor for neighbor in graph[node] if neighbor not in visited)
return False
示例图,使用邻接列表表示
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
print(dfs(graph, 'A', 'F')) 输出: True
```
Java 示例
```java
import java.util.*;
public class DFS {
public static boolean dfs(List Set Stack stack.push(start); while (!stack.isEmpty()) { int node = stack.pop(); if (!visited.contains(node)) { visited.add(node); if (node == end) { return true; } for (int neighbor : graph.get(node)) { if (!visited.contains(neighbor)) { stack.push(neighbor); } } } } return false; } public static void main(String[] args) { List graph.add(Arrays.asList(1, 2)); graph.add(Arrays.asList(0, 3, 4)); graph.add(Arrays.asList(0, 4)); graph.add(Arrays.asList(1, 2)); graph.add(Arrays.asList(1, 3)); graph.add(Arrays.asList(2)); System.out.println(dfs(graph, 0, 4)); // 输出: true } } ``` C++ 示例 ```cpp include include include include using namespace std; bool dfs(const vector unordered_set stack stack.push(start); while (!stack.empty()) { int node = stack.top(); stack.pop(); if (visited.find(node) == visited.end()) { visited.insert(node); if (node == end) { return true; } for (int neighbor : graph[node]) { if (visited.find(neighbor) == visited.end()) { stack.push(neighbor); } } } } return false; } int main() { vector {1, 2}, {0, 3, 4}, {0, 4}, {1, 2}, {1, 3}, {2} }; cout << dfs(graph, 0, 4) << endl; // 输出: 1 (true) return 0; } ``` JavaScript 示例> graph, int start, int end) {
> graph = new ArrayList<>();