栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

B站左程云算法笔记06

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

B站左程云算法笔记06

图

图的存储方式:1.邻接表法2.邻接矩阵

模板 :经典的图结构:点 边。点:值(编号) 、入点、出、邻点和边;边:权值、from、to

public class Graph{
    public HashMap nodes;
    public HashSet edges;

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

public 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<>();
    }
}

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


二维数组转化成熟悉的图结构

public static Graph createGraph(Integer[][] matrix){
        Graph graph = new Graph();
        for(int i = 0; i < matrix.length; i++){
            Integer from = matrix[i][0];
            Integer to = matrix[i][1];
            Integer weight = 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 newEdge = new Edge(weight, fromNode. toNode);
            fromNode.nexts.add(toNode);
            fromNode.out++;
            toNode.in++;
            fromNode.edges.add(newEdge);
            graph.edges.add(newEdge);
    }
        return graph;
}

图的宽度优先遍历

1.利用队列实现

2.从源节点开始依次按照宽度进队列,然后弹出

3.每弹一个点,然后把该节点的所有的没有进过队列的邻接点放入队列

4.直到队列变空

public static void bfs(Node node){
    if(node == null){
        return ;
    }
    Queue queue = new LinkedList<>();
    HashSet 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);
            }
        }
    }
}

广度(深度)优先遍历

1.利用栈实现

2.从源节点开始依次按深度放入栈,然后弹出

3.每弹一个点,把该节点下一个没有进过栈的邻接点放入栈

4.直到栈变空

public static dfs(Node node){
        if(node == null){
            return;
        }
        Stack stack = new Stack<>();
        HashSet 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;
                }
            }
        }
}

拓扑排序算法

适用范围:要求有向图,且有入读为0的节点,且没有环

public static List sortedTopology(Graph graph){
    //key:某一个node
    //value:剩余的入度
    HashMap inMap = new HashMap<>();
    //入度为0的点,才能进这个队列
    Queue zeroInQueue = new LinkedList<>();
    for(Node node : graph.nodes.values()){
        inMap.put(node, node.in);
        if(node.in == 0){
            zeroInQueue.add(node);
        }
    }
    //拓扑排序的结果,依次加入result
    List 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;
}

K算法

生成最小生成树(无向图)

边排序,优先考虑权重最小的边,看有没有成环(结合查询)

public static class mySets{

      public HashMap> setMap;
    
      public MySeys(List nodes) {
        for(Node cur : nodes){
            List set = new ArrayList();
            set.add(cur);
            setMap.put(cur, set);
        }
    }

    public boolean isSameSet(Node from , Node to){
        List fromSet = setMap.get(from);
        List toSet = setMap.get(to);
        return fromSet == toSet;
    }
    
    public void union(Node from , Node to){
        List fromSet = setMap.get(from);
        List toSet = setMap.get(to);

        for(Node toNode :  toSet){
            fromSet.add(toNode);
            setMap.put(toNode, fromSet);
        }
    }
}

k算法代码(并查集结构更快)

public static Set kruskalMST(Graph graph) {
    UnionFind unionFind = new UnionFind();
    unionFind.makeSets(graph.nodes.values());
    PriorityQueue priorityQueue = new PriorityQueue<>(new EdgeComparator());
    for(Edge edge : graph.edges){//M条边
        priorityQueue.add(edge);
    }
    Set result = new HashSet<>();
    while(!priorityQueue.isEmpty()){
        Edge edge = priorityQueue.poll();    
        if(!unionFind.isSameSet(edge.from, edge.to)){
            result.add(edge);
            unionFind.union(edge.frim, edge.to);
        }
    }
    return result;

}

p算法

每次只涉及一个点

public static Set primMST(Graph graph){
    
    //解锁的边进入小根堆
    PriorityQueue priorityQueue = new PriorityQueue<>(new EdgeComparator());

    HashSet set = new HashSet<>();
    
    Set result = new HashSet<>();//依次挑选的边在result

    for(Node node : graph.nodes.values()){
        //node是开始点
        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;//可能的一个新的点
                if(!set.contains(toNode)){//不含有的时候就是新的点
                    set.add(toNode);
                    result.add(edge);
                    for(Edge nextEdge : toNode.edges){
                        priorityQueue.add(nextEdge);
                    }
                }
            }
        }
    }
        return result;
}

Dijkstra算法(适用于没有累加和为负的环,可能会导致锁死的边不对)

public static HashMap dijkstra1(Node head) {
    //从head出发到所有点的最小距离
    //key:从head出发到key
    //value : 从head出发到达key的最小距离
    //如果在表中,没有T的记录,含义是从head出发到T这个点的距离为正无穷
    HashMap distanceMap = new HashMap<>();
    distanceMap.put(head, 0);
    //已经求过距离的节点,存在selectedNodes中,再也不碰
    HashSet selectedNodes = new HashSet<>();
    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);
            }
            distacneMap.put(edge.to, Math.min(distanceMap.get(toNode),distance + egde.weight));
        }
            selectedNodes.add(minNode);
            minNode = getMinDistanceAndUnselectedNode(distanceMap, selectedNodes);
    }
        return distanceMap;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/924914.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号