#
luxiaotao1123
2024-10-24 030c4ad9573cfc6ecda996a7b59d5e16fbb10a42
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package com.zy.acs.manager.common.utils;
 
import java.util.*;
 
/**
 * Breadth-First Search
 * 1.可用于计算最短路径 或者 快速反推二叉树的根节点
 * https://www.bilibili.com/video/BV1Ks411575U/?vd_source=6f04e61f1b57e41e7986c65388d892fb
 * 2.如果连接有权重,那么把Queue变成PriorityQueue => Dijkstra
 * https://www.bilibili.com/video/BV1ts41157Sy/?spm_id_from=333.999.0.0&vd_source=6f04e61f1b57e41e7986c65388d892fb
 */
public class BFS {
 
    private final Map<String, List<String>> graph;
 
    private final Set<String> visited = new HashSet<>();
 
    // 可以通过BFS扫描节点连接关系,来获取节点的最近路径的父节点hash表
    private final Map<String, String> parent = new HashMap<>();
 
    public BFS(Map<String, List<String>> graph) {
        this.graph = graph;
    }
 
    public List<String> execute(String startNode) {
        if (null == graph) {
            throw new RuntimeException("the graph was empty");
        }
 
        List<String> list = new ArrayList<>();
 
        Queue<String> queue = new LinkedList<>();
 
        queue.add(startNode);
        visited.add(startNode);
        parent.put(startNode, null);
 
        while (queue.size() > 0) {
            String node = queue.poll();
 
            List<String> nears = graph.get(node);
            for (String near : nears) {
                if (!visited.contains(near)) {
                    queue.offer(near);
                    visited.add(near);
 
                    parent.put(near, node);
                }
            }
 
            list.add(node);
        }
 
        return list;
    }
 
    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");}});
 
        BFS bfs = new BFS(graph);
        bfs.execute("E");
        String endNode = "B";
        List<String> shortestPath = new ArrayList<>();
        while (endNode != null) {
            shortestPath.add(endNode);
            endNode = bfs.parent.get(endNode);
        }
        Collections.reverse(shortestPath);
 
        System.out.println("shortestPath: " + shortestPath);
    }
 
}