java 图结
包含图的创建和图的宽度优先遍历BFS和图的深度优先遍历DFS
代码
package com.leetcode.Yidongjie;
import java.util.*;
/**
* @author 冀十三(易)
* @date 2022/3/7 21:28
*/
public class Graph {
//存放节点
public HashMap<Integer,Node> nodes;
//存放路径
public HashSet<Edge> edges;
public Graph(){
nodes = new HashMap<>();
edges = new HashSet<>();
}
public static void main(String[] args) {
Integer[][] integers = {{6,4,2},{3,6,7},{4,5,7},{3,4,5,},{2,5,2},{2,5,6},{3,4,6}};
Graph graph = new Graph().createGraph(integers);
Node temp = graph.nodes.get(4);
graph.bfs(temp);
System.out.println("============分割线=============");
graph.dfs(temp);
}
//宽度优先遍历 能走 的先走完
public void bfs(Node node){
if (node.nexts==null){
return;
}
Queue<Node> queue = new LinkedList<Node>();
//这个 set 防止 图里有环的出现
Set<Node> set = new HashSet<Node>();
queue.add(node);
set.add(node);
while (!queue.isEmpty()){
Node cue = queue.poll();
// 出来的时候 处理
System.out.println("处理"+cue);
for(Node next : cue.nexts){
if(!set.contains(next)){
set.add(next);
queue.add(next);
}
}
}
}
// 深度优先遍历 一条道走到黑
public void dfs(Node node){
if (node.nexts == null){
return;
}
Stack<Node> stack = new Stack<Node>();
Set<Node> set = new HashSet<Node>();
set.add(node);
stack.add(node);
// 进去的时候处理
System.out.println("处理"+node);
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);
//不管后面的了
break;
}
}
}
}
//比如[5,0,1]代表0节点到1节点权值 为5
public Graph createGraph(Integer[][] matrix){
Graph graph = new Graph();
for (int i = 0; i < matrix.length; i++){
Integer weight = matrix[i][0];
Integer from = matrix[i][1];
Integer to = matrix[i][2];
//如果不存在 来自的这个节点那么 加这个节点进去
if(!graph.nodes.containsKey(from)){
graph.nodes.put(from,new Node(from));
}
// 如果不存在 去的这个节点 那么 加这个节点进去
if(!graph.nodes.containsKey(to)){
graph.nodes.put(to,new Node(to));
}
//拿到这俩节点
Node fromNode = graph.nodes.get(from);
Node toNode = graph.nodes.get(to);
//根据现 有数据创建新的路径
Edge edge = new Edge(weight,fromNode,toNode);
// 出发电接点的 去向节点 加
fromNode.nexts.add(toNode);
//出发节点的 去向节点数量加
fromNode.out++;
// 出发节点的 指出路径加进去
fromNode.edges.add(edge);
//到达节点的进数加
toNode.in++;
// 将新的 路径加入到图里面
graph.edges.add(edge);
}
return graph;
}
//节点
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;
this.in = 0;
this.out = 0;
this.nexts = new ArrayList<Node>();
this.edges = new ArrayList<Edge>();
}
@Override
public String toString() {
return "Node{" +
"value=" + value +
'}';
}
}
// 路径
public class Edge{
//路径权重
public int weight;
//路径来自
public Node from ;
//路径到达
public Node to;
public Edge(int weight,Node from,Node to){
this.weight = weight;
this.from = from;
this.to = to;
}
}
}