[数据结构]Graph

package MyExc;

import nowcoder.easy.day05.UnionFind;

import java.util.*;

class Node{
public int value;
//入度
public int in;
//出度
public int out;
//邻居节点
public ArrayList nexts;
//从我出发边的集合
public ArrayList edges;

public Node(int value){
    this.value =value;
    in = 0;
    out = 0;
    nexts = new ArrayList<>();
    edges = new ArrayList<>();
}

}

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;
}

}

public class Graph {
public HashMap<Integer,Node> nodes;
public HashSet edges;

public Graph(){
    nodes = new HashMap<>();
    edges = new HashSet<>();
}


public 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.contains(next)){
                set.add(next);
                queue.add(next);
            }
        }
    }
}

public void dfs(Node node){
    if(node==null)
        return;
    Stack<Node> stack = new Stack<>();
    HashSet<Node> set = new HashSet<>();
    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 List<Node> sortedTopology(Graph graph){
    //统计当前节点的入度的map
    HashMap<Node,Integer> inMap = new HashMap<>();
    Queue<Node> zeroInQueue = new LinkedList<>();
    //遍历所有的点的意思
    for(Node node:graph.nodes.values()){
        //把点和该点的入度put进map
        inMap.put(node,node.in);
        if(node.in==0){
            //当前入度为0的点进map
            zeroInQueue.add(node);
        }
    }
    List<Node> result = new ArrayList<>();
    while(!zeroInQueue.isEmpty()){
        Node cur = zeroInQueue.poll();
        result.add(cur);
        //遍历邻居节点
        for(Node next:cur.nexts){
            inMap.put(next,inMap.get(next)-1);
            if(inMap.get(next)==0){
                zeroInQueue.add(next);
            }
        }
    }
    return result;
}

//最小生成树
//必须是无向图
//保证图联通的情况下,边的权值之和最小,而且不能有回路

}

猜你喜欢

转载自www.cnblogs.com/kristse/p/graph.html