图的相关算法(Java代码实现)
图的创建声明
public class Graph {
public HashMap<Integer, Node> nodes; //点集
public HashSet<Edge> edges; //边集
public Graph() {
nodes = new HashMap<>();
edges = new HashSet<>();
}
}
边的声明
public class Edge {
public int weight; //边的权值
public Node from; //边的两个点 from->to
public Node to;
public Edge(int weight, Node from, Node to) {
this.weight = weight;
this.from = from;
this.to = to;
}
}
点的声明
public class Node {
public int value; //点的值
public int in; //入度
public int out; //出度
public ArrayList<Node> nexts; // 直接邻居的点 发散出去的点(对于有向图)
public ArrayList<Edge> edges; //直接邻居的边 发散出去的边(对于有向图)
public Node(int value) {
this.value = value;
in = 0;
out = 0;
nexts = new ArrayList<>();
edges = new ArrayList<>();
}
}
图的生成
public class GraphGenerator {
//matrix 每一个元素都是三列的数据
public static Graph createGraph(Integer matrix[][]) {
Graph graph = new Graph();
for(int i = 0; i < matrix.length; i++) {
//取出每一行 进行赋值
Integer form = matrix[i][0];
Integer to = matrix[i][1];
Integer weight = matrix[i][2];
if(!graph.nodes.containsKey(form)) {
graph.nodes.put(form, new Node(form));
}
if(!graph.nodes.containsKey(to)) {
graph.nodes.put(to, new Node(to));
}
Node fromNode = graph.nodes.get(form);
Node toNode = graph.nodes.get(to);
Edge edge = new Edge(weight, fromNode, toNode); //定义一条边
fromNode.nexts.add(toNode); //添加fromNode的邻居节点
fromNode.out++; //fromNode 的出度++ 1——>2
toNode.in++; //toNode 的入度++
fromNode.edges.add(edge); //添加fromNode的邻居边
graph.edges.add(edge);
}
return graph;
}
}
BFS算法
public class BFS {
public static void bfs(Node node) {
if(node == null) return;
Queue<Node> queue = new LinkedList<Node>();
HashSet<Node> set = new HashSet<Node>(); //set保证点不重复进入队列
queue.add(node);
set.add(node);
while(!queue.isEmpty()) {
Node cur = queue.poll();
System.out.println(cur.value + " "); //可以将处理流程放在这儿
//将cur的邻近点放入队列中
for(Node next : cur.nexts) {
if(!set.contains(next)) {
set.add(next);
queue.add(next);
}
}
}
}
}
DFS算法
//要是不理解的 可以画一个图跟着流程走一遍
public class DFS {
public static void dfs(Node node) {
if(node == null) return;
Stack<Node> stack = new Stack<Node>();
HashSet<Node> set = new HashSet<Node>();
stack.add(node);
set.add(node);
System.out.println(node.value + " ");
while(!stack.isEmpty()) {
Node cur = stack.pop();
for(Node next : cur.nexts) {
if(!set.contains(next)) {
stack.push(cur);
stack.push(next);
set.add(next);
System.out.println(next.value + " "); //可以将处理流程放在这儿
break; //一次只处理一个点
}
}
}
}
}
拓扑排序
public class TopologySort {
public static List<Node> sortedTopology(Graph graph) {
Queue<Node> zeroInQueue = new LinkedList<Node>();
HashMap<Node, Integer> inMap = new HashMap<Node, Integer>();
for(Node node : graph.nodes.values()) {
inMap.put(node, node.in);
//先将入度为0的点放入zeroInQueue中去
if(node.in == 0) zeroInQueue.add(node);
}
List<Node> result = new LinkedList<Node>();
while(!zeroInQueue.isEmpty()) {
Node cur = zeroInQueue.poll();
result.add(cur);
//将cur的邻近点的入度都减1 如果在遇到入度为0的点, 也是放到zeroInQueue中去
for(Node node : cur.nexts) {
//消除cur的影响
inMap.put(node, inMap.get(node) - 1);
if(inMap.get(node) == 0) zeroInQueue.add(node);
}
}
return result;
}
}
Prim算法
public class Prim {
//定义一个比较器 按照边的权重来进行排序
public static class EdgeComparator implements Comparator<Edge>{
@Override
public int compare(Edge o1, Edge o2) {
return o1.weight - o2.weight;
}
}
//prim算法是对于无向图而言的 并且是通过点的延伸方式不断地加入点
public static Set<Edge> primMST(Graph graph){
PriorityQueue<Edge> priorityQueue = new PriorityQueue<Edge>(new EdgeComparator());
HashSet<Node> set = new HashSet<Node>();
Set<Edge> result = new HashSet<Edge>();
//大的循环是为了防止非流通图的情况
for(Node node : graph.nodes.values()) {
if(!set.contains(node)) {
set.add(node);
//将点的邻近边都放入优先级队列中去
for(Edge edge : node.edges) {
priorityQueue.add(edge);
}
while(!priorityQueue.isEmpty()) {
Edge edge = priorityQueue.poll();
Node toNode = edge.to;
//如果set中没有包含对应的点 则将改边加入到result中 并将它的邻近边也加入到优先级队列中去
if(!set.contains(toNode)) {
result.add(edge);
set.add(toNode);
for(Edge edge2 : toNode.edges) {
priorityQueue.add(edge2);
}
}
}
}
}
return result;
}
}
Kruskal算法
//需要用到并查集 后续再来补充
public class Kruskal {
public static class MySets{
public HashMap<Node, List<Node>> setMap; //某一个节点 指向那个集合
public MySets(List<Node> nodes) {
for(Node cur : nodes) {
List<Node> set = new ArrayList<Node>();
set.add(cur);
setMap.put(cur, set);
}
}
public boolean isSameSet(Node from, Node to) {
List<Node> fromSet = setMap.get(from);
List<Node> toSet = setMap.get(to);
return fromSet == toSet;
}
public void union(Node from, Node to) {
List<Node> fromSet = setMap.get(from);
List<Node> toSet = setMap.get(to);
for(Node toNode : toSet) {
fromSet.add(toNode);
setMap.put(toNode, fromSet);
}
}
}
public static class EdgeComparator implements Comparator<Edge>{
@Override
public int compare(Edge o1, Edge o2) {
return o1.weight - o2.weight;
}
}
public static Set<Edge> kruskalMST(Graph graph){
MySets unionFind = new MySets((List<Node>) graph.nodes.values());
PriorityQueue<Edge> priorityQueue = new PriorityQueue<Edge>(new EdgeComparator());
for(Edge edge : graph.edges) {
priorityQueue.add(edge);
}
Set<Edge> result = new HashSet<Edge>();
while(!priorityQueue.isEmpty()) {
Edge edge = priorityQueue.poll();
if(!unionFind.isSameSet(edge.from, edge.to)) {
unionFind.union(edge.from, edge.to);
result.add(edge);
}
}
return result;
}
}
Dijkstra
public class Dijkstra {
public static HashMap<Node, Integer> dijkstra(Node head){
HashMap<Node, Integer> distanceMap = new HashMap<Node, Integer>();
//key 指从head出发到key
//value 指从key到key的最小距离为value
distanceMap.put(head, 0);
// 已经求过距离的点,放在selectedNodes中,以后不再碰
HashSet<Node> selectedNodes = new HashSet<Node>();
Node minNode = getMinDistanceAndUnselectedNode(distanceMap, selectedNodes);
while(minNode != null) {
int distance = distanceMap.get(minNode);
for(Edge edge : minNode.edges) {
Node toNode = edge.to;
//刚开始时的距离均是无穷大
if(!distanceMap.containsKey(toNode)) {
distanceMap.put(toNode, distance + edge.weight);
}
//后者是发现的新路径
else{
distanceMap.put(edge.to, Math.min(distanceMap.get(edge.to), distance + edge.weight));
}
}
selectedNodes.add(minNode);
//得到最小距离且没有选过的点
minNode = getMinDistanceAndUnselectedNode(distanceMap, selectedNodes);
}
return distanceMap;
}
private static Node getMinDistanceAndUnselectedNode(HashMap<Node, Integer> distanceMap,
HashSet<Node> selectedNodes) {
Node minNode = null;
int minDistance = Integer.MAX_VALUE;
for(Entry<Node, Integer> entry : distanceMap.entrySet()) {
Node node = entry.getKey();
int distance = entry.getValue();
if(!selectedNodes.contains(node) && distance < minDistance) {
minDistance = distance;
minNode = node;
}
}
return minNode;
}
}