美文网首页
Dijkstra's 算法

Dijkstra's 算法

作者: Wilbur_ | 来源:发表于2020-10-14 13:04 被阅读0次

    Dijkstra's algorithm, which lets you answer "What's the shortest path to X?" for weighted graphs.


    image.png

    Dijkstra's 就是在weighted graph 中选出最小值路径

    今天完成了每日一题,发现mergesort里面基本的构成就是拆分和merge,这两个你掌握了基本就可以熟练使用了。下面是今天练习的代码:

        public ListNode sortList(ListNode head) {
            if (head == null || head.next == null) {
                return head;
            }
            ListNode mid = findMid(head);
            ListNode left = sortList(head);
            ListNode right = sortList(mid);
            return merge(left, right);
        }
        private ListNode findMid(ListNode head) {
            ListNode slow = null, fast = head;
            while (fast != null && fast.next != null) {
                slow = (slow == null) ? head : slow.next;
                fast = fast.next.next;
            }
            ListNode res = slow.next;
            //cut off (split the listnode)
            slow.next = null;
            return res;
        }
        private ListNode merge(ListNode l1, ListNode l2) {
            ListNode prehead = new ListNode();
            ListNode prev = prehead;
            while (l1 != null && l2 != null) {
                if (l1.val <= l2.val) {
                    prev.next = l1;
                    l1 = l1.next;
                } else {
                    prev.next = l2;
                    l2 = l2.next;
                }
                prev = prev.next;
            }
            prev.next = (l1 == null) ? l2 : l1;
            return prehead.next;
        }
    

    相关文章

      网友评论

          本文标题:Dijkstra's 算法

          本文链接:https://www.haomeiwen.com/subject/ujnmpktx.html