基础概念
图的表示方法多种多样,需要建立自己熟悉的图结构将其各类算法实现,然后遇到图结构之后,将别的结构转化为自己熟悉的结构
in:入度
out:出度
nexts:关联的点
edges:发散出去的边
weight:权重
from:从哪点来
to:到哪点去
把一个二维数组转换为上面的结构
常见算法
图的宽度优先遍历:
利用队列实现
从源节点开始一次按照宽度进队列,然后弹出五
每弹出一个点,就把该节点没有进过队列的邻接点放入队列
直到队列变空
public static void bfs(Node node){
if(node == null){
return ;
}
Queue<Node> queue = new LInkedList<>();
HashSet<Node> set = new HashSet<>();//为了去重的,不然很有可能会无限运行下去
queue.add(node);
set.add(node);
while(!queue.isEmpty()){
Node cur = queue.poll();
System.out.println(cur.value);
for(Node next : cur.nexts){
if(!set.countains(next)){
set.add(next);
queue.add(next);
}
}
}
}
广度优先遍历:
利用栈实现
从源节点开始把节点按照深度放入栈,然后弹出
没弹出一个点,就把该节点下一个没有进入过栈的邻接点放入栈
直到栈变空
public static void bfs(Node node){
if(node == null){
return ;
}
Stack<Node> stack = new Stack<>();
HashSet<Node> set = new HashSet<>();//为了去重的,不然很有可能会无限运行下去
queue.add(node);
set.add(node);
System.out.println(node.value);
while(!stack.isEmpty()){
Node cur = stack.pop();
System.out.println(cur.value);
for(Node next : cur.nexts){
if(!set.countains(next)){
stack.push(cur);
stack.push(next);
set.add(next);
System.out.println(next.value);
break;
}
}
}
}
拓扑排序
拓扑排序,我们可以类比的例子有java中spring的依赖编译,就是生成了一个有向图
无向图算法
krusal算法
仿写:
并查集实现(真):
prim算法
dijkstra算法
使用范围:不能有累加和为负数的环