步骤
- 输入图和起点
- 建立优先队列(按距离起点的距离升序排列)和res(存储结果)
- new一个起点,将其距离起点的距离设为0,入队
- BFS
4.1. 出队 ,如果点没有出现在res,则将其放进去
4.2 将改点相邻的点入队(已经出现在res中的不再入队) - 打印结果
java:
import java.util.*;
public class Main {
public static void main(String[] args){
//起点
String start = "A";
//建立图
HashMap<String, List<Node>> map = new HashMap<>();
map.put("A", Arrays.asList(new Node("B", 5), new Node("C", 1)));
map.put("B", Arrays.asList(new Node("A", 5), new Node("C", 2),new Node("D",1)));
map.put("C", Arrays.asList(new Node("A", 1), new Node("B", 2),new Node("D",4),new Node("E",8)));
map.put("D", Arrays.asList(new Node("B", 1)