”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 加权图类

加权图类

发布于2024-11-07
浏览:390

The WeightedGraph class extends AbstractGraph.
The preceding chapter designed the Graph interface, the AbstractGraph class, and the UnweightedGraph class for modeling graphs. Following this pattern, we design WeightedGraph as a subclass of AbstractGraph, as shown in Figure below.

The WeightedGraph Class

WeightedGraph simply extends AbstractGraph with five constructors for creating concrete WeightedGraph instances. WeightedGraph inherits all methods from AbstractGraph, overrides the clear and addVertex methods, implements a new addEdge method for adding a weighted edge, and also introduces new methods for obtaining minimum spanning trees and for finding all single-source shortest paths. Minimum spanning trees and shortest paths will be introduced in Sections Minimum spanning trees and shortest paths, respectively.

The code below implements WeightedGraph. Edge adjacency lists (lines 38–63) are used internally to store adjacent edges for a vertex. When a WeightedGraph is constructed, its edge adjacency lists are created (lines 47 and 57). The methods getMinimumSpanningTree() (lines 99–138) and getShortestPath() (lines 156–197) will be introduced in upcoming sections.

package demo;
import java.util.*;

public class WeightedGraph extends AbstractGraph {
    /** Construct an empty */
    public WeightedGraph() {}

    /** Construct a WeightedGraph from vertices and edged in arrays */
    public WeightedGraph(V[] vertices, int[][] edges) {
        createWeightedGraph(java.util.Arrays.asList(vertices), edges);
    }

     /** Construct a WeightedGraph from vertices and edges in list */
    public WeightedGraph(int[][] edges, int numberOfVertices) {
        List vertices = new ArrayList();
        for (int i = 0; i  vertices, List edges) {
        createWeightedGraph(vertices, edges);
    }

    /** Construct a WeightedGraph from vertices 0, 1, and edge array */
    public WeightedGraph(List edges, int numberOfVertices) {
        List vertices = new ArrayList();
        for (int i = 0; i  vertices, int[][] edges) {
        this.vertices = vertices;

        for (int i = 0; i ()); // Create a list for vertices
        }

        for (int i = 0; i  vertices, List edges) {
        this.vertices = vertices;

        for (int i = 0; i ()); // Create a list for vertices
        }

        for (WeightedEdge edge: edges) {
            neighbors.get(edge.u).add(edge); // Add an edge into the list
        }
    }

    /** Return the weight on the edge (u, v) */
    public double getWeight(int u, int v) throws Exception {
        for (Edge edge : neighbors.get(u)) {
            if (edge.v == v) {
                return ((WeightedEdge)edge).weight;
            }
        }

        throw new Exception("Edge does not exit");
    }

    /** Display edges with weights */
    public void printWeightedEdges() {
        for (int i = 0; i  T = new ArrayList();

        // Expand T
        while (T.size()  ((WeightedEdge)e).weight) {
                    cost[e.v] = ((WeightedEdge)e).weight;
                    parent[e.v] = u;
                }
            }
        } // End of while

        return new MST(startingVertex, parent, T, totalWeight);
    }

    /** MST is an inner class in WeightedGraph */
    public class MST extends Tree {
        private double totalWeight; // Total weight of all edges in the tree

        public MST(int root, int[] parent, List searchOrder, double totalWeight) {
            super(root, parent, searchOrder);
            this.totalWeight = totalWeight;
        }

        public double getTotalWeight() {
            return totalWeight;
        }
    }

    /** Find single source shortest paths */
    public ShortestPathTree getShortestPath(int sourceVertex) {
        // cost[v] stores the cost of the path from v to the source
        double[] cost = new double[getSize()];
        for (int i = 0; i  T = new ArrayList();

        // Expand T
        while (T.size()  cost[u]   ((WeightedEdge)e).weight) {
                    cost[e.v] = cost[u]   ((WeightedEdge)e).weight;
                    parent[e.v] = u;
                }
            }
        } // End of while

        // Create a ShortestPathTree
        return new ShortestPathTree(sourceVertex, parent, T, cost);
    }

    /** ShortestPathTree is an inner class in WeightedGraph */
    public class ShortestPathTree extends Tree {
        private double[] cost; // cost[v] is the cost from v to source

        /** Construct a path */
        public ShortestPathTree(int source, int[] parent, List searchOrder, double[] cost) {
            super(source, parent, searchOrder);
            this.cost = cost;
        }

        /** Return the cost for a path from the root to vertex v */
        public double getCost(int v) {
            return cost[v];
        }

        /** Print paths from all vertices to the source */
        public void printAllPaths() {
            System.out.println("All shortest paths from "   vertices.get(getRoot())   " are:");
            for (int i = 0; i 



The WeightedGraph class extends the AbstractGraph class (line 3). The properties vertices and neighbors in AbstractGraph are inherited in WeightedGraph.neighbors is a list. Each element is the list is another list that contains edges. For unweighted graph, each edge is an instance of AbstractGraph.Edge. For a weighted graph, each edge is an instance of WeightedEdge. WeightedEdge is a subtype of Edge. So you can add a weighted edge into neighbors.get(i) for a weighted graph (line 47).

The code below gives a test program that creates a graph for the one in Figure below and another graph for the one in Figure below a.

The WeightedGraph Class

The WeightedGraph Class

package demo;

public class TestWeightedGraph {

    public static void main(String[] args) {
        String[] vertices = {"Seattle", "San Francisco", "Los Angeles", "Denver", "Kansas City", "Chicago", "Boston", "New York", "Atlanta", "Miami", "Dallas", "Houston"};

        int[][] edges = {
                {0, 1, 807}, {0, 3, 1331}, {0, 5, 2097},
                {1, 0, 807}, {1, 2, 381}, {1, 3, 1267},
                {2, 1, 381}, {2, 3, 1015}, {2, 4, 1663}, {2, 10, 1435},
                {3, 0, 1331}, {3, 1, 1267}, {3, 2, 1015}, {3, 4, 599}, {3, 5, 1003},
                {4, 2, 1663}, {4, 3, 599}, {4, 5, 533}, {4, 7, 1260}, {4, 8, 864}, {4, 10, 496},
                {5, 0, 2097}, {5, 3, 1003}, {5, 4, 533}, {5, 6, 983}, {5, 7, 787},
                {6, 5, 983}, {6, 7, 214},
                {7, 4, 1260}, {7, 5, 787}, {7, 6, 214}, {7, 8, 888},
                {8, 4, 864}, {8, 7, 888}, {8, 9, 661}, {8, 10, 781}, {8, 11, 810},
                {9, 8, 661}, {9, 11, 1187},
                {10, 2, 1435}, {10, 4, 496}, {10, 8, 781}, {10, 11, 239},
                {11, 8, 810}, {11, 9, 1187}, {11, 10, 239}
        };

        WeightedGraph graph1 = new WeightedGraph(vertices, edges);
        System.out.println("The number of vertices in graph1: "   graph1.getSize());
        System.out.println("The vertex with index 1 is "   graph1.getVertex(1));
        System.out.println("The index for Miami is "   graph1.getIndex("Miami"));
        System.out.println("The edges for graph1:");
        graph1.printWeightedEdges();

        edges = new int[][] {
            {0, 1, 2}, {0, 3, 8},
            {1, 0, 2}, {1, 2, 7}, {1, 3, 3},
            {2, 1, 7}, {2, 3, 4}, {2, 4, 5},
            {3, 0, 8}, {3, 1, 3}, {3, 2, 4}, {3, 4, 6},
            {4, 2, 5}, {4, 3, 6}
        };
        WeightedGraph graph2 = new WeightedGraph(edges, 5);
        System.out.println("\nThe edges for graph2:");
        graph2.printWeightedEdges();
    }
}

The number of vertices in graph1: 12
The vertex with index 1 is San Francisco
The index for Miami is 9
The edges for graph1:
Vertex 0: (0, 1, 807) (0, 3, 1331) (0, 5, 2097)
Vertex 1: (1, 2, 381) (1, 0, 807) (1, 3, 1267)
Vertex 2: (2, 1, 381) (2, 3, 1015) (2, 4, 1663) (2, 10, 1435)
Vertex 3: (3, 4, 599) (3, 5, 1003) (3, 1, 1267)
(3, 0, 1331) (3, 2, 1015)
Vertex 4: (4, 10, 496) (4, 8, 864) (4, 5, 533) (4, 2, 1663)
(4, 7, 1260) (4, 3, 599)
Vertex 5: (5, 4, 533) (5, 7, 787) (5, 3, 1003)
(5, 0, 2097) (5, 6, 983)
Vertex 6: (6, 7, 214) (6, 5, 983)
Vertex 7: (7, 6, 214) (7, 8, 888) (7, 5, 787) (7, 4, 1260)
Vertex 8: (8, 9, 661) (8, 10, 781) (8, 4, 864)
(8, 7, 888) (8, 11, 810)
Vertex 9: (9, 8, 661) (9, 11, 1187)
Vertex 10: (10, 11, 239) (10, 4, 496) (10, 8, 781) (10, 2, 1435)
Vertex 11: (11, 10, 239) (11, 9, 1187) (11, 8, 810)

The edges for graph2:
Vertex 0: (0, 1, 2) (0, 3, 8)
Vertex 1: (1, 0, 2) (1, 2, 7) (1, 3, 3)
Vertex 2: (2, 3, 4) (2, 1, 7) (2, 4, 5)
Vertex 3: (3, 1, 3) (3, 4, 6) (3, 2, 4) (3, 0, 8)
Vertex 4: (4, 2, 5) (4, 3, 6)

The program creates graph1 for the graph in Figure above in lines 3–27. The vertices for graph1 are defined in lines 3–5. The edges for graph1 are defined in lines 7–24. The edges are represented using a two-dimensional array. For each row i in the array, edges[i][0] and edges[i][1] indicate that there is an edge from vertex edges[i][0] to vertex edges[i][1] and the weight for the edge is edges[i][2]. For example, {0, 1, 807} (line 8) represents the edge from vertex 0 (edges[0][0]) to vertex 1 (edges[0][1]) with weight 807 (edges[0][2]). {0, 5, 2097} (line 8) represents the edge from vertex 0 (edges[2][0]) to vertex 5 (edges[2][1]) with weight 2097 (edges[2][2]). Line 35 invokes the printWeightedEdges() method on graph1 to display all edges in graph1.

The program creates the edges for graph2 for the graph in Figure above a in lines 37–44. Line 46 invokes the printWeightedEdges() method on graph2 to display all edges in graph2.

版本声明 本文转载于:https://dev.to/paulike/the-weightedgraph-class-451m?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 如何在 Python 中删除列表元素的尾随字符?
    如何在 Python 中删除列表元素的尾随字符?
    拆分​​列表元素在编程中,经常需要将列表元素拆分为多个组件。一种常见的情况涉及删除尾随字符。假设您有一个字符串列表,其中每个元素都包含一个制表符 ('\t'),后跟其他文本。目标是消除此选项卡及其后面的所有内容,仅保留选项卡之前的文本。考虑以下列表:my_list = ['eleme...
    编程 发布于2024-11-08
  • 以下是根据您的具体要求为您的文章提供的一些标题选项:

* 为什么我的代码不起作用?理解 C++ 中的函数作用域
* C++ 中的函数作用域:为什么我的 HelloWorld() F
    以下是根据您的具体要求为您的文章提供的一些标题选项: * 为什么我的代码不起作用?理解 C++ 中的函数作用域 * C++ 中的函数作用域:为什么我的 HelloWorld() F
    C 中函数声明的范围 在您的代码中,您收到编译错误,因为 HelloWorld() 函数未在与调用它的范围相同。让我们深入研究一下函数作用域的概念并解决这个问题。函数原型,也称为声明,在不提供函数定义的情况下告知编译器函数的存在。在给定的代码中,您尝试调用 HelloWorld(),而不首先在当前作...
    编程 发布于2024-11-08
  • 深入研究 Monty Hall 问题项目:模拟和理解概率概念
    深入研究 Monty Hall 问题项目:模拟和理解概率概念
    欢迎来到 Monty Hall 问题模拟项目的迷人世界!这种实践学习经验将指导您创建基于网络的模拟,该模拟基于流行的游戏节目场景演示有趣的概率谜题。 揭开蒙蒂霍尔问题之谜 蒙蒂·霍尔问题是一个著名的概率难题,几十年来一直让人们感到困惑和着迷。通过参与这个项目,您不仅有机会实现模拟,还...
    编程 发布于2024-11-08
  • 如何在 PHP 中验证 MySQL DELETE 查询是否成功?
    如何在 PHP 中验证 MySQL DELETE 查询是否成功?
    验证 MySQL DELETE 查询是否成功执行 DELETE 操作时,确定其成功执行至关重要。在 PHP 中,您可以采用各种方法来确定 DELETE 查询是否成功。MySQLi 和 PDO使用 MySQLi 或 PDO、mysql_query() 和 PDO::成功删除查询后,exec() 返回不...
    编程 发布于2024-11-08
  • 如何在 Node.js 中提前退出 forEach 循环?
    如何在 Node.js 中提前退出 forEach 循环?
    如何中断 Node.js forEach 循环在需要递归遍历嵌套数据结构并对每个元素执行操作的情况下,您可以使用递归和forEach 的组合。但是,在某些情况下,您可能需要提前退出 forEach 循环。与带有 break 或 continue 语句的常规循环不同,forEach 缺乏停止迭代的内置...
    编程 发布于2024-11-08
  • Day f Brylnt:Next.js 与 Remix
    Day f Brylnt:Next.js 与 Remix
    大家好!我知道这与 Brylnt 的制作并不直接相关,但在决定使用哪个框架时我遇到了一些问题,我想我应该分享一下我对两个流行竞争者的想法:Next.js 和 混音. 这两个框架都很优秀,根据项目的不同,任何一个都可能是正确的选择。由于我使用的是 T3 Stack,其中包括 Next.js,我自然倾向...
    编程 发布于2024-11-08
  • 学习 CSS 网格:包含大量示例的简单指南
    学习 CSS 网格:包含大量示例的简单指南
    Hey there! If you've ever felt like CSS Grid is a bit like trying to solve a Rubik's Cube blindfolded, you're not alone. I'm Eleftheria, and today, I'...
    编程 发布于2024-11-08
  • 如何在 JavaScript 中强制刷新网页并绕过缓存?
    如何在 JavaScript 中强制刷新网页并绕过缓存?
    使用 JavaScript 硬刷新当前页面强制 Web 浏览器通过 JavaScript 硬刷新页面可确保获取页面的全新副本并更新其所有外部资源。 为了实现这一点,JavaScript 提供了一个名为 location.reload(true) 的方法。当传递 true 值时,此方法指示浏览器绕过其...
    编程 发布于2024-11-08
  • 什么是 PATH_INFO 以及它如何增强 PHP Web 应用程序?
    什么是 PATH_INFO 以及它如何增强 PHP Web 应用程序?
    深入研究 PATH_INFO:揭示其在 PHP Web 应用程序中的作用在 Web 开发领域,PHP 是一个强大的工具,用于创建动态和交互式应用程序。它的全部功能之一是名为 PATH_INFO 的神秘变量。尽管经常被提及,但许多人仍然难以理解其确切作用。本文深入研究 PATH_INFO,阐明其目的、...
    编程 发布于2024-11-08
  • 如何使用 Connector .NET 检索 MySQL 中的最后一个插入 ID?
    如何使用 Connector .NET 检索 MySQL 中的最后一个插入 ID?
    使用 Connector .NET 在 MySql 中检索最后一个插入 ID在 MySql 中,最后一个插入 ID 是指分配给新插入的标识符排。该值在某些情况下可能很有价值,例如填充外键关系。最初,假设 MySqlHelper 类的 ExecuteNonQuery 方法返回最后一个插入 ID。然而,...
    编程 发布于2024-11-08
  • 如何在 PHP 中使用 cURL 获取 API 响应?
    如何在 PHP 中使用 cURL 获取 API 响应?
    在 PHP 中使用 cURL 获取 API 响应在 PHP 中,您可以创建一个独立的类,其中包含通过 cURL 调用 API 的函数并获得响应。以下是实现此目的的方法:class ApiRequest { public function getResponse($url) { // Se...
    编程 发布于2024-11-08
  • Ansible 入门 - 初学者指南:日复一日的 DevOps 工具系列
    Ansible 入门 - 初学者指南:日复一日的 DevOps 工具系列
    欢迎来到我们的“50 天 50 个 DevOps 工具”系列的第 30 天!今天,我们将探索 Ansible,它是 DevOps 工具包中最重要的工具之一。本博客将向您介绍 Ansible 的基础知识,分解其关键组件并向您展示如何从简单的示例开始。我们会让事情简单明了,使其成为初学者的完美起点。 ...
    编程 发布于2024-11-08
  • 什么是CPU寄存器
    什么是CPU寄存器
    什么是寄存器: 计算机寄存器是计算机中央处理单元 (CPU) 内的小型高速存储单元,用于临时保存数据和指令,以便在处理过程中快速访问。它们是直接影响 CPU 运算速度和效率的重要组件。 寄存器的访问速度比内存更快,因为它们位于 CPU 内部。这种接近性允许更快的数据检索和处理。 寄存器内存是计算机中...
    编程 发布于2024-11-08
  • 折叠还是双折?这是一个技术问题!
    折叠还是双折?这是一个技术问题!
    我们现在不能停下来,因为我们已经投资了 1 倍,但多年来让我们继续投入 100 倍!斯托克斯! JavaScript 示例 你可能以前听说过,但 Javascript 是在 10 天之内写成的。它的采用率迅速增长,即使在使用该语言几年后,他们也不想引入重大变化……所以,现在该语言已经...
    编程 发布于2024-11-08
  • 动态 Getter 和 Setter 如何增强 JavaScript 的灵活性?
    动态 Getter 和 Setter 如何增强 JavaScript 的灵活性?
    在 JavaScript 中实现动态 Getter 和 Setter:指南在传统 JavaScript 中,getter 和 setter 是为特定属性名称定义的。但是,可以使用 ES2015 中引入的代理创建更灵活的动态 getter 和 setter。使用代理的动态 getter 和 sette...
    编程 发布于2024-11-08

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3