#
luxiaotao1123
2025-01-07 e14f937fac9ba2c9af1fffd4d37f0eba86292575
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.zy.acs.manager.common.utils;
 
import java.util.*;
 
/**
 * Depth-First Search
 * https://www.bilibili.com/video/BV1Ks411575U/?vd_source=6f04e61f1b57e41e7986c65388d892fb
 */
public class DFS {
 
    private final Map<String, List<String>> graph;
 
    private final Set<String> visited = new HashSet<>();
 
    public DFS(Map<String, List<String>> graph) {
        this.graph = graph;
    }
 
    public void execute(String startNode) {
        if (null == graph) {
            throw new RuntimeException("the graph was empty");
        }
        Stack<String> stack = new Stack();
 
        stack.add(startNode);
        visited.add(startNode);
 
        while (stack.size() > 0) {
            String node = stack.pop();
 
            List<String> nears = graph.get(node);
            for (String near : nears) {
                if (!visited.contains(near)) {
                    stack.push(near);
                    visited.add(near);
                }
            }
 
            System.out.println(node);
        }
 
    }
 
    public static void main(String[] args) {
        Map<String, List<String>> graph = new HashMap<>();
        graph.put("A", new ArrayList<String>(){{add("B");add("C");}});
        graph.put("B", new ArrayList<String>(){{add("A");add("C");add("D");}});
        graph.put("C", new ArrayList<String>(){{add("A");add("B");add("D");add("E");}});
        graph.put("D", new ArrayList<String>(){{add("B");add("C");add("E");add("F");}});
        graph.put("E", new ArrayList<String>(){{add("C");add("D");}});
        graph.put("F", new ArrayList<String>(){{add("D");}});
 
        DFS bfs = new DFS(graph);
        bfs.execute("B");
    }
 
 
}