DepthFirstSearch [深度优先搜索]
# 介绍
深度优先搜索算法(英语:Depth-First-Search,DFS)是一种用于遍历或搜索树或图的算法。这个算法会尽可能深地搜索树的分支。当节点 v 的所在边都己被探寻过,搜索将回溯到发现节点 v 的那条边的起始节点。这一过程一直进行到已发现从源节点可达的所有节点为止。如果还存在未被发现的节点,则选择其中一个作为源节点并重复以上过程,整个进程反复进行直到所有节点都被访问为止。这种算法不会根据图的结构等信息调整执行策略。
# 演示
# 实现
# JavaScript
迭代法:
class GraphUnweightedUndirected {
// Unweighted Undirected Graph class
constructor () {
this.connections = {}
}
addNode (node) {
// Function to add a node to the graph (connection represented by set)
this.connections[node] = new Set()
}
addEdge (node1, node2) {
// Function to add an edge (adds the node too if they are not present in the graph)
if (!(node1 in this.connections)) { this.addNode(node1) }
if (!(node2 in this.connections)) { this.addNode(node2) }
this.connections[node1].add(node2)
this.connections[node2].add(node1)
}
DFSIterative (node, value) {
// DFS Function to search if a node with the given value is present in the graph
const stack = [node]
const visited = new Set()
while (stack.length > 0) {
const currNode = stack.pop()
// if the current node contains the value being searched for, true is returned
if (currNode === value) { return true }
// adding the current node to the visited set
visited.add(currNode)
// adding neighbours in the stack
for (const neighbour of this.connections[currNode]) {
if (!visited.has(neighbour)) {
stack.push(neighbour)
}
}
}
return false
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
递归法:
class GraphUnweightedUndirected {
// Unweighted Undirected Graph class
constructor () {
this.connections = {}
}
addNode (node) {
// Function to add a node to the graph (connection represented by set)
this.connections[node] = new Set()
}
addEdge (node1, node2) {
// Function to add an edge (adds the node too if they are not present in the graph)
if (!(node1 in this.connections)) { this.addNode(node1) }
if (!(node2 in this.connections)) { this.addNode(node2) }
this.connections[node1].add(node2)
this.connections[node2].add(node1)
}
DFSRecursive (node, value, visited = new Set()) {
// DFS Function to search if a node with the given value is present in the graph
// checking if the searching node has been found
if (node === value) { return true }
// adding the current node to the visited set
visited.add(node)
// calling the helper function recursively for all unvisited nodes
for (const neighbour of this.connections[node]) {
if (!visited.has(neighbour)) {
if (this.DFSRecursive(neighbour, value, visited)) { return true }
}
}
return false
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# 参考
编辑 (opens new window)
上次更新: 2022/10/18, 09:41:50