<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Paul Ike</title>
    <description>The latest articles on DEV Community by Paul Ike (@paulike).</description>
    <link>https://dev.to/paulike</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1078913%2F6ee3aa0e-a8ed-48a2-9db1-04bcae31c7fd.jpeg</url>
      <title>DEV Community: Paul Ike</title>
      <link>https://dev.to/paulike</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/paulike"/>
    <language>en</language>
    <item>
      <title>Case Study: The Weighted Nine Tails Problem</title>
      <dc:creator>Paul Ike</dc:creator>
      <pubDate>Thu, 05 Sep 2024 17:01:46 +0000</pubDate>
      <link>https://dev.to/paulike/case-study-the-weighted-nine-tails-problem-3n9i</link>
      <guid>https://dev.to/paulike/case-study-the-weighted-nine-tails-problem-3n9i</guid>
      <description>&lt;p&gt;The weighted nine tails problem can be reduced to the weighted shortest path problem.&lt;br&gt;
&lt;a href="https://dev.to/paulike/case-study-the-nine-tails-problem-3m4o"&gt;Section&lt;/a&gt; presented the nine tails problem and solved it using the BFS algorithm. This section presents a variation of the problem and solves it using the shortest-path algorithm.&lt;/p&gt;

&lt;p&gt;The nine tails problem is to find the minimum number of the moves that lead to all coins facing down. Each move flips a head coin and its neighbors. The weighted nine tails problem assigns the number of flips as a weight on each move. For example, you can change the coins in Figure below a to those in Figure below b by flipping the first coin in the first row and its two neighbors. Thus, the weight for this move is &lt;strong&gt;3&lt;/strong&gt;. You can change the coins in Figure below c to Figure below d by flipping the center coin and its four neighbors. So the weight for this move is &lt;strong&gt;5&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnxggp0741yyykme0zxne.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnxggp0741yyykme0zxne.png" alt=" " width="618" height="130"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The weighted nine tails problem can be reduced to finding a shortest path from a starting node to the target node in an edge-weighted graph. The graph has 512 nodes. Create an edge from node &lt;strong&gt;v&lt;/strong&gt; to &lt;strong&gt;u&lt;/strong&gt; if there is a move from node &lt;strong&gt;u&lt;/strong&gt; to node &lt;strong&gt;v&lt;/strong&gt;. Assign the number of flips to be the weight of the edge.&lt;/p&gt;

&lt;p&gt;Recall that in &lt;a href="https://dev.to/paulike/case-study-the-nine-tails-problem-3m4o"&gt;Section&lt;/a&gt; we defined a class &lt;strong&gt;NineTailModel&lt;/strong&gt; for modeling the nine tails problem. We now define a new class named &lt;strong&gt;WeightedNineTailModel&lt;/strong&gt; that extends &lt;strong&gt;NineTailModel&lt;/strong&gt;, as shown in Figure below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxhijfw6d0my82xobcphh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxhijfw6d0my82xobcphh.png" alt=" " width="756" height="463"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;NineTailModel&lt;/strong&gt; class creates a &lt;strong&gt;Graph&lt;/strong&gt; and obtains a &lt;strong&gt;Tree&lt;/strong&gt; rooted at the target node &lt;strong&gt;511&lt;/strong&gt;. &lt;strong&gt;WeightedNineTailModel&lt;/strong&gt; is the same as &lt;strong&gt;NineTailModel&lt;/strong&gt; except that it creates a &lt;strong&gt;WeightedGraph&lt;/strong&gt; and obtains a &lt;strong&gt;ShortestPathTree&lt;/strong&gt; rooted at the target node &lt;strong&gt;511&lt;/strong&gt;. &lt;strong&gt;WeightedNineTailModel&lt;/strong&gt; extends &lt;strong&gt;NineTailModel&lt;/strong&gt;. The method &lt;strong&gt;getEdges()&lt;/strong&gt; finds all edges in the graph. The &lt;strong&gt;getNumberOfFlips(int u, int v)&lt;/strong&gt; method returns the number of flips from node &lt;strong&gt;u&lt;/strong&gt; to node &lt;strong&gt;v&lt;/strong&gt;. The &lt;strong&gt;getNumberOfFlips(int u)&lt;/strong&gt; method returns the number of flips from node &lt;strong&gt;u&lt;/strong&gt; to the target node.&lt;/p&gt;

&lt;p&gt;The code below implements &lt;strong&gt;WeightedNineTailModel&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package demo;
import java.util.*;

public class WeightedNineTailModel extends NineTailModel {
    /** Construct a model */
    public WeightedNineTailModel() {
        // Create edges
        List&amp;lt;WeightedEdge&amp;gt; edges = getEdges();

        // Create a graph
        WeightedGraph&amp;lt;Integer&amp;gt; graph = new WeightedGraph&amp;lt;&amp;gt;(edges, NUMBER_OF_NODES);

        // Obtain a shortest path tree rooted at the target node
        tree = graph.getShortestPath(511);
    }

    /** Create all edges for the graph */
    private List&amp;lt;WeightedEdge&amp;gt; getEdges() {
        // Store edges
        List&amp;lt;WeightedEdge&amp;gt; edges = new ArrayList&amp;lt;&amp;gt;();

        for(int u = 0; u &amp;lt; NUMBER_OF_NODES; u++) {
            for(int k = 0; k &amp;lt; 9; k++) {
                char[] node = getNode(u); // Get the node for vertex u
                if(node[k] == 'H') {
                    int v = getFlippedNode(node, k);
                    int numberOfFlips = getNumberOfFlips(u, v);

                    // Add edge (v, u) for a legal move from node u to node v
                    edges.add(new WeightedEdge(v, u, numberOfFlips));
                }
            }
        }

        return edges;
    }

    private static int getNumberOfFlips(int u, int v) {
        char[] node1 = getNode(u);
        char[] node2 = getNode(v);

        int count = 0; // Count the number of different cells
        for(int i = 0; i &amp;lt; node1.length; i++)
            if(node1[i] != node2[i]) count++;

        return count;
    }

    public int getNumberOfFlips(int u) {
        return (int)((WeightedGraph&amp;lt;Integer&amp;gt;.ShortestPathTree)tree).getCost(u);
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;WeightedNineTailModel&lt;/strong&gt; extends &lt;strong&gt;NineTailModel&lt;/strong&gt; to build a &lt;strong&gt;WeightedGraph&lt;/strong&gt; to model the weighted nine tails problem (lines 10–11). For each node &lt;strong&gt;u&lt;/strong&gt;, the &lt;strong&gt;getEdges()&lt;/strong&gt; method finds a flipped node &lt;strong&gt;v&lt;/strong&gt; and assigns the number of flips as the weight for edge (&lt;strong&gt;v&lt;/strong&gt;, &lt;strong&gt;u&lt;/strong&gt;) (line 30). The &lt;strong&gt;getNumberOfFlips(int u, int v)&lt;/strong&gt; method returns the number of flips from node &lt;strong&gt;u&lt;/strong&gt; to node &lt;strong&gt;v&lt;/strong&gt; (lines 38–47). The number of flips is the number of the different cells between the&lt;br&gt;
two nodes (line 44).&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;WeightedNineTailModel&lt;/strong&gt; obtains a &lt;strong&gt;ShortestPathTree&lt;/strong&gt; rooted at the target node &lt;strong&gt;511&lt;/strong&gt; (line 14). Note that &lt;strong&gt;tree&lt;/strong&gt; is a protected data field defined in &lt;strong&gt;NineTailModel&lt;/strong&gt; and &lt;strong&gt;ShortestPathTree&lt;/strong&gt; is a subclass of &lt;strong&gt;Tree&lt;/strong&gt;. The methods defined in &lt;strong&gt;NineTailModel&lt;/strong&gt; use the &lt;strong&gt;tree&lt;/strong&gt; property.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;getNumberOfFlips(int u)&lt;/strong&gt; method (lines 49–52) returns the number of flips from node &lt;strong&gt;u&lt;/strong&gt; to the target node, which is the cost of the path from node &lt;strong&gt;u&lt;/strong&gt; to the target node. This cost can be obtained by invoking the &lt;strong&gt;getCost(u)&lt;/strong&gt; method defined in the &lt;strong&gt;ShortestPathTree&lt;/strong&gt; class (line 51).&lt;/p&gt;

&lt;p&gt;The code below gives a program that prompts the user to enter an initial node and displays the minimum number of flips to reach the target node.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package demo;

import java.util.Scanner;

public class WeightedNineTail {

    public static void main(String[] args) {
        // Prompt the user to enter nine coins' Hs and Ts
        System.out.print("Enter the initial nine coins Hs and Ts: ");
        Scanner input = new Scanner(System.in);
        String s = input.nextLine();
        char[] initialNode = s.toCharArray();

        WeightedNineTailModel model = new WeightedNineTailModel();
        java.util.List&amp;lt;Integer&amp;gt; path = model.getShortestPath(NineTailModel.getIndex(initialNode));

        System.out.println("The steps to flip the coins are ");
        for (int i = 0; i &amp;lt; path.size(); i++)
            NineTailModel.printNode(NineTailModel.getNode(path.get(i).intValue()));

        System.out.println("The number of flips is " +  model.getNumberOfFlips(NineTailModel.getIndex(initialNode)));
    }

}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Enter an initial nine coins Hs and Ts: HHHTTTHHH&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;The steps to flip the coins are&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;HHH&lt;br&gt;
TTT&lt;br&gt;
HHH&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;HHH&lt;br&gt;
THT&lt;br&gt;
TTT&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;TTT&lt;br&gt;
TTT&lt;br&gt;
TTT&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;The number of flips is 8&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The program prompts the user to enter an initial node with nine letters with a combination of &lt;strong&gt;H&lt;/strong&gt;s and &lt;strong&gt;T&lt;/strong&gt;s as a string in line 8, obtains an array of characters from the string (line 9), creates a model (line 11), obtains the shortest path from the initial node to the target node (lines 12–13), displays the nodes in the path (lines 16–17), and invokes &lt;strong&gt;getNumberOfFlips&lt;/strong&gt; to get the number of flips needed to reach the target node (line 20).&lt;/p&gt;

</description>
      <category>java</category>
      <category>programming</category>
      <category>beginners</category>
      <category>learning</category>
    </item>
    <item>
      <title>Finding Shortest Paths</title>
      <dc:creator>Paul Ike</dc:creator>
      <pubDate>Thu, 05 Sep 2024 16:41:27 +0000</pubDate>
      <link>https://dev.to/paulike/finding-shortest-paths-5hfl</link>
      <guid>https://dev.to/paulike/finding-shortest-paths-5hfl</guid>
      <description>&lt;p&gt;The shortest path between two vertices is a path with the minimum total weights.&lt;br&gt;
Given a graph with nonnegative weights on the edges, a well-known algorithm for finding a &lt;em&gt;shortest path&lt;/em&gt; between two vertices was discovered by Edsger Dijkstra, a Dutch computer scientist. In order to find a shortest path from vertex &lt;strong&gt;s&lt;/strong&gt; to vertex &lt;strong&gt;v&lt;/strong&gt;, &lt;em&gt;Dijkstra’s algorithm&lt;/em&gt; finds the shortest path from &lt;strong&gt;s&lt;/strong&gt; to all vertices. So &lt;em&gt;Dijkstra’s algorithm&lt;/em&gt; is known as a &lt;em&gt;single-source&lt;/em&gt; shortest path algorithm. The algorithm uses &lt;strong&gt;cost[v]&lt;/strong&gt; to store the cost of a &lt;em&gt;shortest path&lt;/em&gt; from vertex &lt;strong&gt;v&lt;/strong&gt; to the source vertex &lt;strong&gt;s&lt;/strong&gt;. &lt;strong&gt;cost[s]&lt;/strong&gt; is &lt;strong&gt;0&lt;/strong&gt;. Initially assign infinity to &lt;strong&gt;cost[v]&lt;/strong&gt; for all other vertices. The algorithm repeatedly finds a vertex &lt;strong&gt;u&lt;/strong&gt; in &lt;strong&gt;V – T&lt;/strong&gt; with the smallest &lt;strong&gt;cost[u]&lt;/strong&gt; and moves &lt;strong&gt;u&lt;/strong&gt; to &lt;strong&gt;T&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The algorithm is described in code below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Input: a graph G = (V, E) with non-negative weights
Output: a shortest path tree with the source vertex s as the root
 1 ShortestPathTree getShortestPath(s) {
 2 Let T be a set that contains the vertices whose
 3 paths to s are known; Initially T is empty;
 4 Set cost[s] = 0; and cost[v] = infinity for all other vertices in V;
 5
 6 while (size of T &amp;lt; n) {
 7 Find u not in T with the smallest cost[u];
 8 Add u to T;
 9 for (each v not in T and (u, v) in E)
10 if (cost[v] &amp;gt; cost[u] + w(u, v)) {
11 cost[v] = cost[u] + w(u, v); parent[v] = u;
12 }
13 }
14 }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This algorithm is very similar to Prim’s for finding a minimum spanning tree. Both algorithms divide the vertices into two sets: &lt;strong&gt;T&lt;/strong&gt; and &lt;strong&gt;V - T&lt;/strong&gt;. In the case of Prim’s algorithm, set &lt;strong&gt;T&lt;/strong&gt; contains the vertices that are already added to the tree. In the case of Dijkstra’s, set &lt;strong&gt;T&lt;/strong&gt; contains the vertices whose shortest paths to the source have been found. Both algorithms repeatedly find a vertex from &lt;strong&gt;V – T&lt;/strong&gt; and add it to &lt;strong&gt;T&lt;/strong&gt;. In the case of Prim’s algorithm, the vertex is adjacent to some vertex in the set with the minimum weight on the edge. In Dijkstra’s algorithm, the vertex is adjacent to some vertex in the set with the minimum total cost to the source.&lt;/p&gt;

&lt;p&gt;The algorithm starts by setting &lt;strong&gt;cost[s]&lt;/strong&gt; to &lt;strong&gt;0&lt;/strong&gt; (line 4), sets &lt;strong&gt;cost[v]&lt;/strong&gt; to infinity for all other vertices. It then continuously adds a vertex (say &lt;strong&gt;u&lt;/strong&gt;) from &lt;strong&gt;V – T&lt;/strong&gt; into &lt;strong&gt;T&lt;/strong&gt; with smallest &lt;strong&gt;cost[u]&lt;/strong&gt; (lines 7–8), as shown in Figure below a. After adding &lt;strong&gt;u&lt;/strong&gt; to &lt;strong&gt;T&lt;/strong&gt;, the algorithm updates &lt;strong&gt;cost[v]&lt;/strong&gt; and &lt;strong&gt;parent[v]&lt;/strong&gt; for each &lt;strong&gt;v&lt;/strong&gt; not in &lt;strong&gt;T&lt;/strong&gt; if &lt;strong&gt;(u, v)&lt;/strong&gt; is in &lt;strong&gt;T&lt;/strong&gt; and &lt;strong&gt;cost[v] &amp;gt; cost[u] + w(u, v)&lt;/strong&gt; (lines 10–11).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fy1eodtu51dzpgkd7iaj2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fy1eodtu51dzpgkd7iaj2.png" alt=" " width="760" height="246"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let us illustrate Dijkstra’s algorithm using the graph in Figure below a. Suppose the source vertex is &lt;strong&gt;1&lt;/strong&gt;. Therefore, &lt;strong&gt;cost[1] = 0&lt;/strong&gt; and the costs for all other vertices are initially ∞, as shown in Figure below b. We use the &lt;strong&gt;parent[i]&lt;/strong&gt; to denote the parent of &lt;strong&gt;i&lt;/strong&gt; in the path. For convenience, set the parent of the source node to &lt;strong&gt;-1&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftx83o4mo2djmjfqs3j3p.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftx83o4mo2djmjfqs3j3p.png" alt=" " width="660" height="243"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Initially set &lt;strong&gt;T&lt;/strong&gt; is empty. The algorithm selects the vertex with the smallest cost. In this case, the vertex is &lt;strong&gt;1&lt;/strong&gt;. The algorithm adds &lt;strong&gt;1&lt;/strong&gt; to &lt;strong&gt;T&lt;/strong&gt;, as shown in Figure below a. Afterwards, it adjusts the cost for each vertex adjacent to &lt;strong&gt;1&lt;/strong&gt;. The cost for vertices 2, 0, 6, and 3 and their parents are now updated, as shown, as shown in Figure below b.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fo2mjxp8vl4kzsixf5ebb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fo2mjxp8vl4kzsixf5ebb.png" alt=" " width="668" height="264"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Vertices &lt;strong&gt;2&lt;/strong&gt;, &lt;strong&gt;0&lt;/strong&gt;, &lt;strong&gt;6&lt;/strong&gt;, and &lt;strong&gt;3&lt;/strong&gt; are adjacent to the source vertex, and vertex &lt;strong&gt;2&lt;/strong&gt; is the one in &lt;strong&gt;V-T&lt;/strong&gt; with the smallest cost, so add &lt;strong&gt;2&lt;/strong&gt; to &lt;strong&gt;T&lt;/strong&gt;, as shown in Figure below and update the cost and parent for vertices in &lt;strong&gt;V-T&lt;/strong&gt; and adjacent to &lt;strong&gt;2&lt;/strong&gt;. &lt;strong&gt;cost[0]&lt;/strong&gt; is now updated to &lt;strong&gt;6&lt;/strong&gt; and its parent is set to &lt;strong&gt;2&lt;/strong&gt;. The arrow line from &lt;strong&gt;1&lt;/strong&gt; to &lt;strong&gt;2&lt;/strong&gt; indicates that &lt;strong&gt;1&lt;/strong&gt; is the parent of &lt;strong&gt;2&lt;/strong&gt; after &lt;strong&gt;2&lt;/strong&gt; is added into &lt;strong&gt;T&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw1u6po5xh46wa58lsgod.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw1u6po5xh46wa58lsgod.png" alt=" " width="636" height="220"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now &lt;strong&gt;T&lt;/strong&gt; contains {&lt;strong&gt;1&lt;/strong&gt;, &lt;strong&gt;2&lt;/strong&gt;}. Vertex &lt;strong&gt;0&lt;/strong&gt; is the one in &lt;strong&gt;V-T&lt;/strong&gt; with the smallest cost, so add &lt;strong&gt;0&lt;/strong&gt; to &lt;strong&gt;T&lt;/strong&gt;, as shown in Figure below and update the cost and parent for vertices in &lt;strong&gt;V-T&lt;/strong&gt; and adjacent to &lt;strong&gt;0&lt;/strong&gt; if applicable. &lt;strong&gt;cost[5]&lt;/strong&gt; is now updated to &lt;strong&gt;10&lt;/strong&gt; and its parent is set to &lt;strong&gt;0&lt;/strong&gt; and &lt;strong&gt;cost[6]&lt;/strong&gt; is now updated to &lt;strong&gt;8&lt;/strong&gt; and its parent is set to &lt;strong&gt;0&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnsgibf16gen78a4wdu4j.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnsgibf16gen78a4wdu4j.png" alt=" " width="647" height="226"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now &lt;strong&gt;T&lt;/strong&gt; contains {&lt;strong&gt;1&lt;/strong&gt;, &lt;strong&gt;2&lt;/strong&gt;, &lt;strong&gt;0&lt;/strong&gt;}. Vertex &lt;strong&gt;6&lt;/strong&gt; is the one in &lt;strong&gt;V-T&lt;/strong&gt; with the smallest cost, so add &lt;strong&gt;6&lt;/strong&gt; to &lt;strong&gt;T&lt;/strong&gt;, as shown in Figure below and update the cost and parent for vertices in &lt;strong&gt;V-T&lt;/strong&gt; and adjacent to &lt;strong&gt;6&lt;/strong&gt; if applicable.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxy5y1gix84n4pa83vpg1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxy5y1gix84n4pa83vpg1.png" alt=" " width="641" height="241"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now &lt;strong&gt;T&lt;/strong&gt; contains {&lt;strong&gt;1&lt;/strong&gt;, &lt;strong&gt;2&lt;/strong&gt;, &lt;strong&gt;0&lt;/strong&gt;, &lt;strong&gt;6&lt;/strong&gt;}. Vertex &lt;strong&gt;3&lt;/strong&gt; or &lt;strong&gt;5&lt;/strong&gt; is is the one in &lt;strong&gt;V-T&lt;/strong&gt; with the smallest cost. You may add either &lt;strong&gt;3&lt;/strong&gt; or &lt;strong&gt;5&lt;/strong&gt; into &lt;strong&gt;T&lt;/strong&gt;. Let us add &lt;strong&gt;3&lt;/strong&gt; to &lt;strong&gt;T&lt;/strong&gt;, as shown in Figure below and update the cost and parent for vertices in &lt;strong&gt;V-T&lt;/strong&gt; and adjacent to &lt;strong&gt;3&lt;/strong&gt; if applicable. &lt;strong&gt;cost[4]&lt;/strong&gt; is now updated to &lt;strong&gt;18&lt;/strong&gt; and its parent is set to &lt;strong&gt;3&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fidwr0p8m964pknvw0s3w.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fidwr0p8m964pknvw0s3w.png" alt=" " width="642" height="248"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now &lt;strong&gt;T&lt;/strong&gt; contains {&lt;strong&gt;1&lt;/strong&gt;, &lt;strong&gt;2&lt;/strong&gt;, &lt;strong&gt;0&lt;/strong&gt;, &lt;strong&gt;6&lt;/strong&gt;, &lt;strong&gt;3&lt;/strong&gt;}. Vertex &lt;strong&gt;5&lt;/strong&gt; is the one in &lt;strong&gt;V-T&lt;/strong&gt; with the smallest cost, so add &lt;strong&gt;5&lt;/strong&gt; to &lt;strong&gt;T&lt;/strong&gt;, as shown in Figure below and update the cost and parent for vertices in &lt;strong&gt;V-T&lt;/strong&gt; and adjacent to &lt;strong&gt;5&lt;/strong&gt; if applicable. &lt;strong&gt;cost[4]&lt;/strong&gt; is now updated to &lt;strong&gt;10&lt;/strong&gt; and its parent is set to &lt;strong&gt;5&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm2z44nkbzymwpjn7ffby.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm2z44nkbzymwpjn7ffby.png" alt=" " width="666" height="231"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now &lt;strong&gt;T&lt;/strong&gt; contains {&lt;strong&gt;1&lt;/strong&gt;, &lt;strong&gt;2&lt;/strong&gt;, &lt;strong&gt;0&lt;/strong&gt;, &lt;strong&gt;6&lt;/strong&gt;, &lt;strong&gt;3&lt;/strong&gt;, &lt;strong&gt;5&lt;/strong&gt;}. Vertex &lt;strong&gt;4&lt;/strong&gt; is the one in &lt;strong&gt;V-T&lt;/strong&gt; with the smallest cost, so add &lt;strong&gt;4&lt;/strong&gt; to &lt;strong&gt;T&lt;/strong&gt;, as shown in Figure below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe1k9t8bysl9veusn3hri.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe1k9t8bysl9veusn3hri.png" alt=" " width="658" height="215"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As you can see, the algorithm essentially finds all shortest paths from a source vertex, which produces a tree rooted at the source vertex. We call this tree a &lt;em&gt;single-source all-shortest-path tree&lt;/em&gt; (or simply a &lt;em&gt;shortest-path tree&lt;/em&gt;). To model this tree, define a class named &lt;strong&gt;ShortestPathTree&lt;/strong&gt; that extends the &lt;strong&gt;Tree&lt;/strong&gt; class, as shown in Figure  below. &lt;strong&gt;ShortestPathTree&lt;/strong&gt; is defined as an inner class in &lt;strong&gt;WeightedGraph&lt;/strong&gt; in lines 200–224 in &lt;a href="https://dev.to/paulike/the-weightedgraph-class-451m"&gt;WeightedGraph.java&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fajlbr4ohoycu8n4zzmf0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fajlbr4ohoycu8n4zzmf0.png" alt=" " width="758" height="209"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;getShortestPath(int sourceVertex)&lt;/strong&gt; method was implemented in lines 156–197 in &lt;a href="https://dev.to/paulike/the-weightedgraph-class-451m"&gt;WeightedGraph.java&lt;/a&gt;. The method sets &lt;strong&gt;cost[sourceVertex]&lt;/strong&gt; to &lt;strong&gt;0&lt;/strong&gt; (line 162) and &lt;strong&gt;cost[v]&lt;/strong&gt; to infinity for all other vertices (lines 159–161). The parent of &lt;strong&gt;sourceVertex&lt;/strong&gt; is set to &lt;strong&gt;-1&lt;/strong&gt; (line 166). &lt;strong&gt;T&lt;/strong&gt; is a list that stores the vertices added into the shortest path tree (line 169). We use a list for &lt;strong&gt;T&lt;/strong&gt; rather than a set in order to record the order of the vertices added to &lt;strong&gt;T&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Initially, &lt;strong&gt;T&lt;/strong&gt; is empty. To expand &lt;strong&gt;T&lt;/strong&gt;, the method performs the following operations:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Find the vertex &lt;strong&gt;u&lt;/strong&gt; with the smallest &lt;strong&gt;cost[u]&lt;/strong&gt; (lines 175–181) and add it into &lt;strong&gt;T&lt;/strong&gt; (line 183).&lt;/li&gt;
&lt;li&gt;After adding &lt;strong&gt;u&lt;/strong&gt; in &lt;strong&gt;T&lt;/strong&gt;, update &lt;strong&gt;cost[v]&lt;/strong&gt; and &lt;strong&gt;parent[v]&lt;/strong&gt; for each &lt;strong&gt;v&lt;/strong&gt; adjacent to &lt;strong&gt;u&lt;/strong&gt; in &lt;strong&gt;V-T&lt;/strong&gt; if &lt;strong&gt;cost[v] &amp;gt; cost[u] + w(u, v)&lt;/strong&gt; (lines 186–192).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Once all vertices from &lt;strong&gt;s&lt;/strong&gt; are added to &lt;strong&gt;T&lt;/strong&gt;, an instance of &lt;strong&gt;ShortestPathTree&lt;/strong&gt; is created (line 196).&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;ShortestPathTree&lt;/strong&gt; class extends the &lt;strong&gt;Tree&lt;/strong&gt; class (line 200). To create an instance of &lt;strong&gt;ShortestPathTree&lt;/strong&gt;, pass &lt;strong&gt;sourceVertex&lt;/strong&gt;, &lt;strong&gt;parent&lt;/strong&gt;, &lt;strong&gt;T&lt;/strong&gt;, and &lt;strong&gt;cost&lt;/strong&gt; (lines 204–205). &lt;strong&gt;sourceVertex&lt;/strong&gt; becomes the root in the tree. The data fields &lt;strong&gt;root&lt;/strong&gt;, &lt;strong&gt;parent&lt;/strong&gt;, and &lt;strong&gt;searchOrder&lt;/strong&gt; are defined in the &lt;strong&gt;Tree&lt;/strong&gt; class, which is an inner class defined in &lt;strong&gt;AbstractGraph&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Note that testing whether a vertex &lt;strong&gt;i&lt;/strong&gt; is in &lt;strong&gt;T&lt;/strong&gt; by invoking &lt;strong&gt;T.contains(i)&lt;/strong&gt; takes &lt;strong&gt;O(n)&lt;/strong&gt; time, since &lt;strong&gt;T&lt;/strong&gt; is a list. Therefore, the overall time complexity for this implemention is O(n^3).&lt;/p&gt;

&lt;p&gt;Dijkstra’s algorithm is a combination of a greedy algorithm and dynamic programming. It is a greedy algorithm in the sense that it always adds a new vertex that has the shortest distance to the source. It stores the shortest distance of each known vertex to the source and uses it later to avoid redundant computing, so Dijkstra’s algorithm also uses dynamic programming.&lt;/p&gt;

&lt;p&gt;The code below gives a test program that displays the shortest paths from Chicago to all other cities in Figure below and the shortest paths from vertex &lt;strong&gt;3&lt;/strong&gt; to all vertices for the graph in Figure below a, respectively.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft6n032zolcx68aiopj2q.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft6n032zolcx68aiopj2q.png" alt=" " width="754" height="368"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbwnefvx4ztjmjr7nwg7b.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbwnefvx4ztjmjr7nwg7b.png" alt=" " width="655" height="163"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package demo;

public class TestShortestPath {

    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&amp;lt;String&amp;gt; graph1 = new WeightedGraph&amp;lt;&amp;gt;(vertices, edges);
        WeightedGraph&amp;lt;String&amp;gt;.ShortestPathTree tree1 = graph1.getShortestPath(graph1.getIndex("Chicago"));
        tree1.printAllPaths();

        // Display shortest paths from Houston to Chicago       
        System.out.println("Shortest path from Houston to Chicago: ");
        java.util.List&amp;lt;String&amp;gt; path = tree1.getPath(graph1.getIndex("Houston"));
        for(String s: path) {
            System.out.print(s + " ");
        }

        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&amp;lt;Integer&amp;gt; graph2 = new WeightedGraph&amp;lt;&amp;gt;(edges, 5);
        WeightedGraph&amp;lt;Integer&amp;gt;.ShortestPathTree tree2 = graph2.getShortestPath(3);
        System.out.println("\n");
        tree2.printAllPaths();
    }

}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;All shortest paths from Chicago are:&lt;br&gt;
A path from Chicago to Seattle: Chicago Seattle (cost: 2097.0)&lt;br&gt;
A path from Chicago to San Francisco:&lt;br&gt;
 Chicago Denver San Francisco (cost: 2270.0)&lt;br&gt;
A path from Chicago to Los Angeles:&lt;br&gt;
 Chicago Denver Los Angeles (cost: 2018.0)&lt;br&gt;
A path from Chicago to Denver: Chicago Denver (cost: 1003.0)&lt;br&gt;
A path from Chicago to Kansas City: Chicago Kansas City (cost: 533.0)&lt;br&gt;
A path from Chicago to Chicago: Chicago (cost: 0.0)&lt;br&gt;
A path from Chicago to Boston: Chicago Boston (cost: 983.0)&lt;br&gt;
A path from Chicago to New York: Chicago New York (cost: 787.0)&lt;br&gt;
A path from Chicago to Atlanta:&lt;br&gt;
 Chicago Kansas City Atlanta (cost: 1397.0)&lt;br&gt;
A path from Chicago to Miami:&lt;br&gt;
 Chicago Kansas City Atlanta Miami (cost: 2058.0)&lt;br&gt;
A path from Chicago to Dallas: Chicago Kansas City Dallas (cost: 1029.0)&lt;br&gt;
A path from Chicago to Houston:&lt;br&gt;
 Chicago Kansas City Dallas Houston (cost: 1268.0)&lt;br&gt;
Shortest path from Houston to Chicago:&lt;br&gt;
 Houston Dallas Kansas City Chicago&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;All shortest paths from 3 are:&lt;br&gt;
A path from 3 to 0: 3 1 0 (cost: 5.0)&lt;br&gt;
A path from 3 to 1: 3 1 (cost: 3.0)&lt;br&gt;
A path from 3 to 2: 3 2 (cost: 4.0)&lt;br&gt;
A path from 3 to 3: 3 (cost: 0.0)&lt;br&gt;
A path from 3 to 4: 3 4 (cost: 6.0)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The program creates a weighted graph for Figure above in line 27. It then invokes the &lt;strong&gt;getShortestPath(graph1.getIndex("Chicago"))&lt;/strong&gt; method to return a &lt;strong&gt;Path&lt;/strong&gt; object that contains all shortest paths from Chicago. Invoking &lt;strong&gt;printAllPaths()&lt;/strong&gt; on the &lt;strong&gt;ShortestPathTree&lt;/strong&gt; object displays all the paths (line 30).&lt;/p&gt;

&lt;p&gt;The graphical illustration of all shortest paths from Chicago is shown in Figure below. The shortest paths from Chicago to the cities are found in this order: Kansas City, New York, Boston, Denver, Dallas, Houston, Atlanta, Los Angeles, Miami, Seattle, and San Francisco.&lt;/p&gt;

</description>
      <category>java</category>
      <category>programming</category>
      <category>learning</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Minimum Spanning Trees</title>
      <dc:creator>Paul Ike</dc:creator>
      <pubDate>Thu, 05 Sep 2024 15:46:04 +0000</pubDate>
      <link>https://dev.to/paulike/minimum-spanning-trees-1epo</link>
      <guid>https://dev.to/paulike/minimum-spanning-trees-1epo</guid>
      <description>&lt;p&gt;A minimum spanning tree of a graph is a spanning tree with the minimum total weights.&lt;/p&gt;

&lt;p&gt;A graph may have many spanning trees. Suppose that the edges are weighted. A minimum spanning tree has the minimum total weights. For example, the trees in Figures below b, c, d are spanning trees for the graph in Figure a. The trees in Figures c and d are minimum spanning trees.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkjg49eks6wea9aiakaif.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkjg49eks6wea9aiakaif.png" alt=" " width="700" height="354"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The problem of finding a minimum spanning tree has many applications. Consider a company with branches in many cities. The company wants to lease telephone lines to connect all the branches together. The phone company charges different amounts of money to connect different pairs of cities. There are many ways to connect all branches together. The cheapest way is to find a spanning tree with the minimum total rates.&lt;/p&gt;

&lt;h2&gt;
  
  
  Minimum Spanning Tree Algorithms
&lt;/h2&gt;

&lt;p&gt;How do you find a minimum spanning tree? There are several well-known algorithms for doing so. This section introduces &lt;em&gt;Prim’s algorithm&lt;/em&gt;. Prim’s algorithm starts with a spanning tree &lt;strong&gt;T&lt;/strong&gt; that contains an arbitrary vertex. The algorithm expands the tree by repeatedly adding a vertex with the &lt;em&gt;lowest-cost&lt;/em&gt; edge incident to a vertex already in the tree. Prim’s algorithm is a greedy algorithm, and it is described in code below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Input: A connected undirected weighted G = (V, E) with non-negative weights
 Output: MST (a minimum spanning tree)
 1 MST minimumSpanningTree() {
 2 Let T be a set for the vertices in the spanning tree;
 3 Initially, add the starting vertex to T;
 4
 5 while (size of T &amp;lt; n) {
 6 Find u in T and v in V – T with the smallest weight
 7 on the edge (u, v), as shown in Figure 29.6;
 8 Add v to T and set parent[v] = u;
 9 }
10 }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The algorithm starts by adding the starting vertex into &lt;strong&gt;T&lt;/strong&gt;. It then continuously adds a vertex (say &lt;strong&gt;v&lt;/strong&gt;) from &lt;strong&gt;V – T&lt;/strong&gt; into &lt;strong&gt;T&lt;/strong&gt;. &lt;strong&gt;v&lt;/strong&gt; is the vertex that is adjacent to the vertex in &lt;strong&gt;T&lt;/strong&gt; with the smallest weight on the edge. For example, there are five edges connecting vertices in &lt;strong&gt;T&lt;/strong&gt; and &lt;strong&gt;V – T&lt;/strong&gt; as shown in Figure below, and (&lt;strong&gt;u&lt;/strong&gt;, &lt;strong&gt;v&lt;/strong&gt;) is the one with the smallest weight.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxwsg9o6v7opor7w4cwza.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxwsg9o6v7opor7w4cwza.png" alt=" " width="499" height="177"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Consider the graph in Figure below. The algorithm adds the vertices to &lt;strong&gt;T&lt;/strong&gt; in this order:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnbfmiycrdmx7weizhdxy.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnbfmiycrdmx7weizhdxy.png" alt=" " width="673" height="563"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Add vertex &lt;strong&gt;0&lt;/strong&gt; to &lt;strong&gt;T&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Add vertex &lt;strong&gt;5&lt;/strong&gt; to &lt;strong&gt;T&lt;/strong&gt;, since &lt;strong&gt;Edge(5, 0, 5)&lt;/strong&gt; has the smallest weight among all edges incident to a vertex in &lt;strong&gt;T&lt;/strong&gt;, as shown in Figure a. The arrow line from &lt;strong&gt;0&lt;/strong&gt; to &lt;strong&gt;5&lt;/strong&gt; indicates that &lt;strong&gt;0&lt;/strong&gt; is the parent of &lt;strong&gt;5&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Add vertex &lt;strong&gt;1&lt;/strong&gt; to &lt;strong&gt;T&lt;/strong&gt;, since &lt;strong&gt;Edge(1, 0, 6)&lt;/strong&gt; has the smallest weight among all edges incident to a vertex in &lt;strong&gt;T&lt;/strong&gt;, as shown in Figure b.&lt;/li&gt;
&lt;li&gt;Add vertex &lt;strong&gt;6&lt;/strong&gt; to &lt;strong&gt;T&lt;/strong&gt;, since &lt;strong&gt;Edge(6, 1, 7)&lt;/strong&gt; has the smallest weight among all edges incident to a vertex in &lt;strong&gt;T&lt;/strong&gt;, as shown in Figure c.&lt;/li&gt;
&lt;li&gt;Add vertex &lt;strong&gt;2&lt;/strong&gt; to &lt;strong&gt;T&lt;/strong&gt;, since &lt;strong&gt;Edge(2, 6, 5)&lt;/strong&gt; has the smallest weight among all edges incident to a vertex in &lt;strong&gt;T&lt;/strong&gt;, as shown in Figure d.&lt;/li&gt;
&lt;li&gt;Add vertex &lt;strong&gt;4&lt;/strong&gt; to &lt;strong&gt;T&lt;/strong&gt;, since &lt;strong&gt;Edge(4, 6, 7)&lt;/strong&gt; has the smallest weight among all edges incident to a vertex in &lt;strong&gt;T&lt;/strong&gt;, as shown in Figure e.&lt;/li&gt;
&lt;li&gt;Add vertex &lt;strong&gt;3&lt;/strong&gt; to &lt;strong&gt;T&lt;/strong&gt;, since &lt;strong&gt;Edge(3, 2, 8)&lt;/strong&gt; has the smallest weight among all edges incident to a vertex in &lt;strong&gt;T&lt;/strong&gt;, as shown in Figure f.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A minimum spanning tree is not unique. For example, both (c) and (d) in Figure below are minimum spanning trees for the graph in Figure a. However, if the weights are distinct, the graph has a unique minimum spanning tree.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8tckxxy8gif7rqcpmxre.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8tckxxy8gif7rqcpmxre.png" alt=" " width="700" height="354"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Assume that the graph is connected and undirected. If a graph is not connected or directed, the algorithm will not work. You can modify the algorithm to find a spanning forest for any undirected graph. A spanning forest is a graph in which each connected component is a tree.&lt;/p&gt;

&lt;h2&gt;
  
  
  Refining Prim’s MST Algorithm
&lt;/h2&gt;

&lt;p&gt;To make it easy to identify the next vertex to add into the tree, we use &lt;strong&gt;cost[v]&lt;/strong&gt; to store the cost of adding a vertex &lt;strong&gt;v&lt;/strong&gt; to the spanning tree &lt;strong&gt;T&lt;/strong&gt;. Initially &lt;strong&gt;cost[s]&lt;/strong&gt; is &lt;strong&gt;0&lt;/strong&gt; for a starting vertex and assign infinity to &lt;strong&gt;cost[v]&lt;/strong&gt; for all other vertices. The algorithm repeatedly finds a vertex &lt;strong&gt;u&lt;/strong&gt; in &lt;strong&gt;V – T&lt;/strong&gt; with the smallest &lt;strong&gt;cost[u]&lt;/strong&gt; and moves &lt;strong&gt;u&lt;/strong&gt; to &lt;strong&gt;T&lt;/strong&gt;. The refined version of the alogrithm is given in code below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Input: A connected undirected weighted G = (V, E) with non-negative weights
Output: a minimum spanning tree with the starting vertex s as the root
 1 MST getMinimumSpanngingTree(s) {
 2 Let T be a set that contains the vertices in the spanning tree;
 3 Initially T is empty;
 4 Set cost[s] = 0; and cost[v] = infinity for all other vertices in V;
 5
 6 while (size of T &amp;lt; n) {
 7 Find u not in T with the smallest cost[u];
 8 Add u to T;
 9 for (each v not in T and (u, v) in E)
10 if (cost[v] &amp;gt; w(u, v)) { // Adjust cost[v]
11 cost[v] = w(u, v); parent[v] = u;
12 }
13 }
14 }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Implementation of the MST Algorithm
&lt;/h2&gt;

&lt;p&gt;The &lt;strong&gt;getMinimumSpanningTree(int v)&lt;/strong&gt; method is defined in the &lt;strong&gt;WeightedGraph&lt;/strong&gt; class. It returns an instance of the &lt;strong&gt;MST&lt;/strong&gt; class, as shown in Figure below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fggftu5vnax8goahomfac.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fggftu5vnax8goahomfac.png" alt=" " width="759" height="437"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;MST&lt;/strong&gt; class is defined as an inner class in the &lt;strong&gt;WeightedGraph&lt;/strong&gt; class, which extends the &lt;strong&gt;Tree&lt;/strong&gt; class, as shown in Figure below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fywdsaejntpg1239gy556.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fywdsaejntpg1239gy556.png" alt=" " width="759" height="186"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;Tree&lt;/strong&gt; class was shown in Figure below. The &lt;strong&gt;MST&lt;/strong&gt; class was implemented in lines 141–153 in &lt;a href="https://dev.to/paulike/the-weightedgraph-class-451m"&gt;WeightedGraph.java&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F95r9q2q7uurdvhvexeai.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F95r9q2q7uurdvhvexeai.png" alt=" " width="752" height="267"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The refined version of the Prim’s algoruthm greatly simplifies the implementation. The &lt;strong&gt;getMinimumSpanningTree&lt;/strong&gt; method was implemented using the refined version of the Prim’s algorithm in lines 99–138 in Listing 29.2. The &lt;strong&gt;getMinimumSpanningTree(int startingVertex)&lt;/strong&gt; method sets &lt;strong&gt;cost[startingVertex]&lt;/strong&gt; to &lt;strong&gt;0&lt;/strong&gt; (line 105) and &lt;strong&gt;cost[v]&lt;/strong&gt; to infinity for all other vertices (lines 102–104). The parent of &lt;strong&gt;startingVertex&lt;/strong&gt; is set to &lt;strong&gt;-1&lt;/strong&gt; (line 108). &lt;strong&gt;T&lt;/strong&gt; is a list that stores the vertices added into the spanning tree (line 111). We use a list for &lt;strong&gt;T&lt;/strong&gt; rather than a set in order to record the order of the vertices added to &lt;strong&gt;T&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Initially, &lt;strong&gt;T&lt;/strong&gt; is empty. To expand &lt;strong&gt;T&lt;/strong&gt;, the method performs the following operations:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Find the vertex &lt;strong&gt;u&lt;/strong&gt; with the smallest &lt;strong&gt;cost[u]&lt;/strong&gt; (lines 118–123 and add it into &lt;strong&gt;T&lt;/strong&gt; (line 125).&lt;/li&gt;
&lt;li&gt;After adding &lt;strong&gt;u&lt;/strong&gt; in &lt;strong&gt;T&lt;/strong&gt;, update &lt;strong&gt;cost[v]&lt;/strong&gt; and &lt;strong&gt;parent[v]&lt;/strong&gt; for each &lt;strong&gt;v&lt;/strong&gt; adjacent to &lt;strong&gt;u&lt;/strong&gt; in &lt;strong&gt;V-T&lt;/strong&gt; if &lt;strong&gt;cost[v] &amp;gt; w(u, v)&lt;/strong&gt; (lines 129–134).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;After a new vertex is added to &lt;strong&gt;T&lt;/strong&gt;, &lt;strong&gt;totalWeight&lt;/strong&gt; is updated (line 126). Once all vertices are added to &lt;strong&gt;T&lt;/strong&gt;, an instance of &lt;strong&gt;MST&lt;/strong&gt; is created (line 137). Note that the method will not work if the graph is not connected. However, you can modify it to obtain a partial MST.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;MST&lt;/strong&gt; class extends the &lt;strong&gt;Tree&lt;/strong&gt; class (line 141). To create an instance of &lt;strong&gt;MST&lt;/strong&gt;, pass &lt;strong&gt;root&lt;/strong&gt;, &lt;strong&gt;parent&lt;/strong&gt;, &lt;strong&gt;T&lt;/strong&gt;, and &lt;strong&gt;totalWeight&lt;/strong&gt; (lines 144-145). The data fields &lt;strong&gt;root&lt;/strong&gt;, &lt;strong&gt;parent&lt;/strong&gt;, and &lt;strong&gt;searchOrder&lt;/strong&gt; are defined in the &lt;strong&gt;Tree&lt;/strong&gt; class, which is an inner class defined in &lt;strong&gt;AbstractGraph&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Note that testing whether a vertex &lt;strong&gt;i&lt;/strong&gt; is in &lt;strong&gt;T&lt;/strong&gt; by invoking &lt;strong&gt;T.contains(i)&lt;/strong&gt; takes &lt;strong&gt;O(n)&lt;/strong&gt; time, since &lt;strong&gt;T&lt;/strong&gt; is a list. Therefore, the overall time complexity for this implemention is O(n3).&lt;/p&gt;

&lt;p&gt;The code below gives a test program that displays minimum spanning trees for the graph in Figure below and the graph in Figure below a, respectively.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft6n032zolcx68aiopj2q.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft6n032zolcx68aiopj2q.png" alt=" " width="754" height="368"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbwnefvx4ztjmjr7nwg7b.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbwnefvx4ztjmjr7nwg7b.png" alt=" " width="655" height="163"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package demo;

public class TestMinimumSpanningTree {

    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&amp;lt;String&amp;gt; graph1 = new WeightedGraph&amp;lt;&amp;gt;(vertices, edges);
        WeightedGraph&amp;lt;String&amp;gt;.MST tree1 = graph1.getMinimumSpanningTree();
        System.out.println("Total weight is " + tree1.getTotalWeight());
        tree1.printTree();

        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&amp;lt;Integer&amp;gt; graph2 = new WeightedGraph&amp;lt;&amp;gt;(edges, 5);
        WeightedGraph&amp;lt;Integer&amp;gt;.MST tree2 = graph2.getMinimumSpanningTree(1);
        System.out.println("\nTotal weight is " + tree2.getTotalWeight());
        tree2.printTree();
    }

}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Total weight is 6513.0&lt;br&gt;
Root is: Seattle&lt;br&gt;
Edges: (Seattle, San Francisco) (San Francisco, Los Angeles)&lt;br&gt;
 (Los Angeles, Denver) (Denver, Kansas City) (Kansas City, Chicago)&lt;br&gt;
 (New York, Boston) (Chicago, New York) (Dallas, Atlanta)&lt;br&gt;
 (Atlanta, Miami) (Kansas City, Dallas) (Dallas, Houston)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Total weight is 14.0&lt;br&gt;
Root is: 1&lt;br&gt;
Edges: (1, 0) (3, 2) (1, 3) (2, 4)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The program creates a weighted graph for Figure above in line 27. It then invokes &lt;strong&gt;getMinimumSpanningTree()&lt;/strong&gt; (line 28) to return an &lt;strong&gt;MST&lt;/strong&gt; that represents a minimum spanning tree for the graph. Invoking &lt;strong&gt;printTree()&lt;/strong&gt; (line 30) on the &lt;strong&gt;MST&lt;/strong&gt; object displays the edges in the tree. Note that &lt;strong&gt;MST&lt;/strong&gt; is a subclass of &lt;strong&gt;Tree&lt;/strong&gt;. The &lt;strong&gt;printTree()&lt;/strong&gt; method is defined in the &lt;strong&gt;Tree&lt;/strong&gt; class.&lt;/p&gt;

&lt;p&gt;The graphical illustration of the minimum spanning tree is shown in Figure below. The vertices are added to the tree in this order: Seattle, San Francisco, Los Angeles, Denver, Kansas City, Dallas, Houston, Chicago, New York, Boston, Atlanta, and Miami.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fghtqd71i5nrsw4bxi5l7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fghtqd71i5nrsw4bxi5l7.png" alt=" " width="755" height="407"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>java</category>
      <category>programming</category>
      <category>learning</category>
      <category>beginners</category>
    </item>
    <item>
      <title>The WeightedGraph Class</title>
      <dc:creator>Paul Ike</dc:creator>
      <pubDate>Thu, 05 Sep 2024 15:26:26 +0000</pubDate>
      <link>https://dev.to/paulike/the-weightedgraph-class-451m</link>
      <guid>https://dev.to/paulike/the-weightedgraph-class-451m</guid>
      <description>&lt;p&gt;The &lt;strong&gt;WeightedGraph&lt;/strong&gt; class extends &lt;strong&gt;AbstractGraph&lt;/strong&gt;.&lt;br&gt;
The preceding chapter designed the &lt;strong&gt;Graph&lt;/strong&gt; interface, the &lt;strong&gt;AbstractGraph&lt;/strong&gt; class, and the &lt;strong&gt;UnweightedGraph&lt;/strong&gt; class for modeling graphs. Following this pattern, we design &lt;strong&gt;WeightedGraph&lt;/strong&gt; as a subclass of &lt;strong&gt;AbstractGraph&lt;/strong&gt;, as shown in Figure below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F55dm7vs352n243unixsm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F55dm7vs352n243unixsm.png" alt=" " width="758" height="437"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;WeightedGraph&lt;/strong&gt; simply extends &lt;strong&gt;AbstractGraph&lt;/strong&gt; with five constructors for creating concrete &lt;strong&gt;WeightedGraph&lt;/strong&gt; instances. &lt;strong&gt;WeightedGraph&lt;/strong&gt; inherits all methods from &lt;strong&gt;AbstractGraph&lt;/strong&gt;, overrides the &lt;strong&gt;clear&lt;/strong&gt; and &lt;strong&gt;addVertex&lt;/strong&gt; methods, implements a new &lt;strong&gt;addEdge&lt;/strong&gt; 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 &lt;a href="https://dev.to/paulike/minimum-spanning-trees-1epo"&gt;Minimum spanning trees&lt;/a&gt; and  &lt;a href="https://dev.to/paulike/finding-shortest-paths-5hfl"&gt;shortest paths&lt;/a&gt;, respectively.&lt;/p&gt;

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

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package demo;
import java.util.*;

public class WeightedGraph&amp;lt;V&amp;gt; extends AbstractGraph&amp;lt;V&amp;gt; {
    /** 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&amp;lt;V&amp;gt; vertices = new ArrayList&amp;lt;&amp;gt;();
        for (int i = 0; i &amp;lt; numberOfVertices; i++)
            vertices.add((V)(new Integer(i)));

        createWeightedGraph(vertices, edges);
    }

    /** Construct a WeightedGraph for vertices 0, 1, 2 and edge list */
    public WeightedGraph(List&amp;lt;V&amp;gt; vertices, List&amp;lt;WeightedEdge&amp;gt; edges) {
        createWeightedGraph(vertices, edges);
    }

    /** Construct a WeightedGraph from vertices 0, 1, and edge array */
    public WeightedGraph(List&amp;lt;WeightedEdge&amp;gt; edges, int numberOfVertices) {
        List&amp;lt;V&amp;gt; vertices = new ArrayList&amp;lt;&amp;gt;();
        for (int i = 0; i &amp;lt; numberOfVertices; i++)
            vertices.add((V)(new Integer(i)));

        createWeightedGraph(vertices, edges);
    }

    /** Create adjacency lists from edge arrays */
    private void createWeightedGraph(List&amp;lt;V&amp;gt; vertices, int[][] edges) {
        this.vertices = vertices;

        for (int i = 0; i &amp;lt; vertices.size(); i++) {
            neighbors.add(new ArrayList&amp;lt;Edge&amp;gt;()); // Create a list for vertices
        }

        for (int i = 0; i &amp;lt; edges.length; i++) {
            neighbors.get(edges[i][0]).add(new WeightedEdge(edges[i][0], edges[i][1], edges[i][2]));
        }
    }

    /** Create adjacency lists from edge lists */
    private void createWeightedGraph(List&amp;lt;V&amp;gt; vertices, List&amp;lt;WeightedEdge&amp;gt; edges) {
        this.vertices = vertices;

        for (int i = 0; i &amp;lt; vertices.size(); i++) {
            neighbors.add(new ArrayList&amp;lt;Edge&amp;gt;()); // 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 &amp;lt; getSize(); i++) {
            System.out.print(getVertex(i) + " (" + i + "): ");
            for (Edge edge : neighbors.get(i)) {
                System.out.print("(" + edge.u + ", " + edge.v + ", " + ((WeightedEdge)edge).weight + ") ");
            }

            System.out.println();
        }
    }

    /** Add edges to the weighted graph */
    public boolean addEdge(int u, int v, double weight) {
        return addEdge(new WeightedEdge(u, v, weight));
    }

    /** Get a minimum spanning tree rooted at vertex 0 */
    public MST getMinimumSpanningTree() {
        return getMinimumSpanningTree(0);
    }

    /** Get a minimum spanning tree rooted at a specified vertex */
    public MST getMinimumSpanningTree(int startingVertex) {
        // cost[v] stores the cost by adding v to the tree
        double[] cost = new double[getSize()];
        for (int i = 0; i &amp;lt; cost.length; i++) {
            cost[i] = Double.POSITIVE_INFINITY; // Initial cost
        }
        cost[startingVertex] = 0; // Cost of source is 0

        int[] parent = new int[getSize()]; // Parent of a vertex
        parent[startingVertex] = -1; // startingVertex is the root
        double totalWeight = 0; // Total weight of the tree thus far

        List&amp;lt;Integer&amp;gt; T = new ArrayList&amp;lt;&amp;gt;();

        // Expand T
        while (T.size() &amp;lt; getSize()) {
            // Find smallest cost v in V - T
            int u = -1; // Vertex to be determined
            double currentMinCost = Double.POSITIVE_INFINITY;
            for (int i = 0; i &amp;lt; getSize(); i++) {
                if (!T.contains(i) &amp;amp;&amp;amp; cost[i] &amp;lt; currentMinCost) {
                    currentMinCost = cost[i];
                    u = i;
                }
            }

            T.add(u); // Add a new vertex to T
            totalWeight += cost[u]; // Add cost[u] to the tree

            // Adjust cost[v] for v that is adjacent to u and v in V - T
            for (Edge e : neighbors.get(u)) {
                if (!T.contains(e.v) &amp;amp;&amp;amp; cost[e.v] &amp;gt; ((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&amp;lt;Integer&amp;gt; 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 &amp;lt; cost.length; i++) {
            cost[i] = Double.POSITIVE_INFINITY; // Initial cost set to infinity
        }
        cost[sourceVertex] = 0; // Cost of source is 0

        // parent[v] stores the previous vertex of v in the path
        int[] parent = new int[getSize()];
        parent[sourceVertex] = -1; // The parent of source is set to -1

        // T stores the vertices whose path found so far
        List&amp;lt;Integer&amp;gt; T = new ArrayList&amp;lt;&amp;gt;();

        // Expand T
        while (T.size() &amp;lt; getSize()) {
            // Find smallest cost v in V - T
            int u = -1; // Vertex to be determined
            double currentMinCost = Double.POSITIVE_INFINITY;
            for (int i = 0; i &amp;lt; getSize(); i++) {
                if (!T.contains(i) &amp;amp;&amp;amp; cost[i] &amp;lt; currentMinCost) {
                    currentMinCost = cost[i];
                    u = i;
                }
            }

            T.add(u); // Add a new vertex to T

            // Adjust cost[v] for v that is adjacent to u and v in V - T
            for (Edge e : neighbors.get(u)) {
                if (!T.contains(e.v) &amp;amp;&amp;amp; cost[e.v] &amp;gt; 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&amp;lt;Integer&amp;gt; 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 &amp;lt; cost.length; i++) {
                printPath(i); // Print a path from i to the source
                System.out.println("(cost: " + cost[i] + ")"); // Path cost
            }
        }
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



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

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft6n032zolcx68aiopj2q.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft6n032zolcx68aiopj2q.png" alt=" " width="754" height="368"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbwnefvx4ztjmjr7nwg7b.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbwnefvx4ztjmjr7nwg7b.png" alt=" " width="655" height="163"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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&amp;lt;String&amp;gt; graph1 = new WeightedGraph&amp;lt;&amp;gt;(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&amp;lt;Integer&amp;gt; graph2 = new WeightedGraph&amp;lt;&amp;gt;(edges, 5);
        System.out.println("\nThe edges for graph2:");
        graph2.printWeightedEdges();
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



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

&lt;p&gt;&lt;code&gt;The edges for graph2:&lt;br&gt;
Vertex 0: (0, 1, 2) (0, 3, 8)&lt;br&gt;
Vertex 1: (1, 0, 2) (1, 2, 7) (1, 3, 3)&lt;br&gt;
Vertex 2: (2, 3, 4) (2, 1, 7) (2, 4, 5)&lt;br&gt;
Vertex 3: (3, 1, 3) (3, 4, 6) (3, 2, 4) (3, 0, 8)&lt;br&gt;
Vertex 4: (4, 2, 5) (4, 3, 6)&lt;/code&gt;&lt;/p&gt;

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

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

</description>
      <category>java</category>
      <category>programming</category>
      <category>learning</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Representing Weighted Graphs</title>
      <dc:creator>Paul Ike</dc:creator>
      <pubDate>Thu, 05 Sep 2024 15:08:03 +0000</pubDate>
      <link>https://dev.to/paulike/representing-weighted-graphs-151c</link>
      <guid>https://dev.to/paulike/representing-weighted-graphs-151c</guid>
      <description>&lt;p&gt;Weighted edges can be stored in adjacency lists.&lt;/p&gt;

&lt;p&gt;There are two types of weighted graphs: vertex weighted and edge weighted. In a &lt;em&gt;vertex-weighted graph&lt;/em&gt;, each vertex is assigned a weight. In an &lt;em&gt;edge-weighted graph&lt;/em&gt;, each edge is assigned a weight. Of the two types, edge-weighted graphs have more applications. This chapter considers edge-weighted graphs.&lt;/p&gt;

&lt;p&gt;Weighted graphs can be represented in the same way as unweighted graphs, except that you have to represent the weights on the edges. As with unweighted graphs, the vertices in weighted graphs can be stored in an array. This section introduces three representations for the edges in weighted graphs.&lt;/p&gt;

&lt;h2&gt;
  
  
  Representing Weighted Edges: Edge Array
&lt;/h2&gt;

&lt;p&gt;Weighted edges can be represented using a two-dimensional array. For example, you can store all the edges in the graph in Figure below (a) using the array in Figure below (b).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5zn4zyv4c73ga5sh3oyh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5zn4zyv4c73ga5sh3oyh.png" alt=" " width="655" height="163"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Weights can be of any type: &lt;strong&gt;Integer&lt;/strong&gt;, &lt;strong&gt;Double&lt;/strong&gt;, &lt;strong&gt;BigDecimal&lt;/strong&gt;, and so on. You can use a two-dimensional array of the &lt;strong&gt;Object&lt;/strong&gt; type to represent weighted edges as follows:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Object[][] edges = {&lt;br&gt;
 {new Integer(0), new Integer(1), new SomeTypeForWeight(2)},&lt;br&gt;
 {new Integer(0), new Integer(3), new SomeTypeForWeight(8)},&lt;br&gt;
 ...&lt;br&gt;
};&lt;/code&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Weighted Adjacency Matrices
&lt;/h2&gt;

&lt;p&gt;Assume that the graph has n vertices. You can use a two-dimensional n * n matrix, say &lt;strong&gt;weights&lt;/strong&gt;, to represent the weights on edges. &lt;strong&gt;weights[i][j]&lt;/strong&gt; represents the weight on edge (&lt;strong&gt;i&lt;/strong&gt;, &lt;strong&gt;j&lt;/strong&gt;). If vertices &lt;strong&gt;i&lt;/strong&gt; and &lt;strong&gt;j&lt;/strong&gt; are not connected, &lt;strong&gt;weights[i][j]&lt;/strong&gt; is &lt;strong&gt;null&lt;/strong&gt;. For example, the weights in the graph in Figure above (a) can be represented using an adjacency matrix as follows:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fma5tmj6srcnrwell2pbb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fma5tmj6srcnrwell2pbb.png" alt=" " width="646" height="144"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Adjacency Lists
&lt;/h2&gt;

&lt;p&gt;Another way to represent the edges is to define edges as objects. The &lt;strong&gt;AbstractGraph.Edge&lt;/strong&gt; class was defined to represent an unweighted edge in &lt;a href="https://dev.to/paulike/modeling-graphs-5d01"&gt;AbstractGraph.java&lt;/a&gt;. For weighted edges, we define the &lt;strong&gt;WeightedEdge&lt;/strong&gt; class as shown in code below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgpt5pvwb3ii1zrsp5084.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgpt5pvwb3ii1zrsp5084.png" alt=" " width="800" height="454"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;AbstractGraph.Edge&lt;/strong&gt; is an inner class defined in the &lt;strong&gt;AbstractGraph&lt;/strong&gt; class. It represents an edge from vertex &lt;strong&gt;u&lt;/strong&gt; to &lt;strong&gt;v&lt;/strong&gt;. &lt;strong&gt;WeightedEdge&lt;/strong&gt; extends &lt;strong&gt;AbstractGraph.Edge&lt;/strong&gt; with a new property &lt;strong&gt;weight&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;To create a &lt;strong&gt;WeightedEdge&lt;/strong&gt; object, use &lt;strong&gt;new WeightedEdge(i, j, w)&lt;/strong&gt;, where &lt;strong&gt;w&lt;/strong&gt; is the weight on edge (&lt;strong&gt;i&lt;/strong&gt;, &lt;strong&gt;j&lt;/strong&gt;). Often you need to compare the weights of the edges. For this reason, the &lt;strong&gt;WeightedEdge&lt;/strong&gt; class implements the &lt;strong&gt;Comparable&lt;/strong&gt; interface.&lt;/p&gt;

&lt;p&gt;For unweighted graphs, we use adjacency lists to represent edges. For weighted graphs, we still use adjacency lists, the adjacency lists for the vertices in the graph in Figure below a can be represented as follows:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;java.util.List&amp;lt;WeightedEdge&amp;gt;[] list = new java.util.List[5];&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frsbjgpenm2h32ecs8q5i.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frsbjgpenm2h32ecs8q5i.png" alt=" " width="655" height="163"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcw4rv2m686an5eo146xt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcw4rv2m686an5eo146xt.png" alt=" " width="678" height="157"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;list[i]&lt;/strong&gt; stores all edges adjacent to vertex &lt;strong&gt;i&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;For flexibility, we will use an array list rather than a fixed-sized array to represent &lt;strong&gt;list&lt;/strong&gt; as follows:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;List&amp;lt;List&amp;lt;WeightedEdge&amp;gt;&amp;gt; list = new java.util.ArrayList&amp;lt;&amp;gt;();&lt;/code&gt;&lt;/p&gt;

</description>
      <category>java</category>
      <category>programming</category>
      <category>learning</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Weighted Graphs and Applications</title>
      <dc:creator>Paul Ike</dc:creator>
      <pubDate>Thu, 05 Sep 2024 14:50:39 +0000</pubDate>
      <link>https://dev.to/paulike/weighted-graphs-and-applications-3g22</link>
      <guid>https://dev.to/paulike/weighted-graphs-and-applications-3g22</guid>
      <description>&lt;p&gt;A graph is a weighted graph if each edge is assigned a weight. Weighted graphs have many practical applications.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fh1qfzu26maqxx9i04iby.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fh1qfzu26maqxx9i04iby.png" alt=" " width="755" height="332"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Figure above assumes that the graph represents the number of flights among cities. You can apply the BFS to find the fewest number of flights between two cities. Assume that the edges represent the driving distances among the cities as shown in Figure below. How do you find the minimal total distances for connecting all cities? How do you find the shortest path between two cities? This chapter will address these questions. The former is known as the &lt;em&gt;minimum spanning tree (MST) problem&lt;/em&gt; and the latter as the &lt;em&gt;shortest path problem&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fphgrul0o895ro96b433c.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fphgrul0o895ro96b433c.png" alt=" " width="754" height="368"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The preceding chapter introduced the concept of graphs. You learned how to represent edges using edge arrays, edge lists, adjacency matrices, and adjacency lists, and how to model a graph using the &lt;strong&gt;Graph&lt;/strong&gt; interface, the &lt;strong&gt;AbstractGraph&lt;/strong&gt; class, and the &lt;strong&gt;UnweightedGraph&lt;/strong&gt; class. The preceding chapter also introduced two important techniques for traversing graphs: depth-first search and breadth-first search, and applied traversal to solve practical problems. The following posts will introduce weighted graphs. You will learn the algorithm for finding a minimum spanning tree in &lt;a href="https://dev.to/paulike/minimum-spanning-trees-1epo"&gt;post&lt;/a&gt; and the algorithm for finding shortest paths in &lt;a href="https://dev.to/paulike/finding-shortest-paths-5hfl"&gt;post&lt;/a&gt; .&lt;/p&gt;

</description>
      <category>java</category>
      <category>programming</category>
      <category>learning</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Case Study: The Nine Tails Problem</title>
      <dc:creator>Paul Ike</dc:creator>
      <pubDate>Fri, 09 Aug 2024 16:51:32 +0000</pubDate>
      <link>https://dev.to/paulike/case-study-the-nine-tails-problem-3m4o</link>
      <guid>https://dev.to/paulike/case-study-the-nine-tails-problem-3m4o</guid>
      <description>&lt;p&gt;The nine tails problem can be reduced to the shortest path problem.&lt;br&gt;
The nine tails problem is as follows. Nine coins are placed in a three-by-three matrix with some face up and some face down. A legal move is to take a coin that is face up and reverse it, together with the coins adjacent to it (this does not include coins that are diagonally adjacent). Your task is to find the minimum number of moves that lead to all coins being face down. For example, start with the nine coins as shown in Figure below (a). After you flip the second coin in the last row, the nine coins are now as shown in Figure below (b). After you flip the second coin in the first row, the nine coins are all face down, as shown in Figure below (c).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhnbjxm0jc8n0gv74tif1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhnbjxm0jc8n0gv74tif1.png" alt=" " width="495" height="99"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We will write a program that prompts the user to enter an initial state of the nine coins and displays the solution, as shown in the following sample run.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Enter the initial nine coins Hs and Ts: HHHTTTHHH&lt;br&gt;
The steps to flip the coins are&lt;br&gt;
HHH&lt;br&gt;
TTT&lt;br&gt;
HHH&lt;br&gt;
HHH&lt;br&gt;
THT&lt;br&gt;
TTT&lt;br&gt;
TTT&lt;br&gt;
TTT&lt;br&gt;
TTT&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Each state of the nine coins represents a node in the graph. For example, the three states in Figure above correspond to three nodes in the graph. For convenience, we use a 3 * 3 matrix to represent all nodes and use &lt;strong&gt;0&lt;/strong&gt; for heads and &lt;strong&gt;1&lt;/strong&gt; for tails. Since there are nine cells and each cell is either &lt;strong&gt;0&lt;/strong&gt; or &lt;strong&gt;1&lt;/strong&gt;, there are a total of 2^9 (512) nodes, labeled &lt;strong&gt;0&lt;/strong&gt;, &lt;strong&gt;1&lt;/strong&gt;, . . . , and &lt;strong&gt;511&lt;/strong&gt;, as shown in Figure below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbkhmyx0db3ez4wkcwr3w.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbkhmyx0db3ez4wkcwr3w.png" alt=" " width="487" height="104"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We assign an edge from node &lt;strong&gt;v&lt;/strong&gt; to &lt;strong&gt;u&lt;/strong&gt; if there is a legal move from &lt;strong&gt;u&lt;/strong&gt; to &lt;strong&gt;v&lt;/strong&gt;. Figure below shows a partial graph. Note there is an edge from &lt;strong&gt;511&lt;/strong&gt; to &lt;strong&gt;47&lt;/strong&gt;, since you can flip a cell in node &lt;strong&gt;47&lt;/strong&gt; to become node &lt;strong&gt;511&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7ut3o2zebnoh7mb0n3c2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7ut3o2zebnoh7mb0n3c2.png" alt=" " width="648" height="181"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The last node in Figure below represents the state of nine face-down coins. For convenience, we call this last node the &lt;em&gt;target node&lt;/em&gt;. Thus, the target node is labeled &lt;strong&gt;511&lt;/strong&gt;. Suppose the initial state of the nine tails problem corresponds to the node &lt;strong&gt;s&lt;/strong&gt;. The problem is reduced to finding a shortest path from node &lt;strong&gt;s&lt;/strong&gt; to the target node, which is equivalent to finding a shortest path from node &lt;strong&gt;s&lt;/strong&gt; to the target node in a BFS tree rooted at the target node.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbkhmyx0db3ez4wkcwr3w.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbkhmyx0db3ez4wkcwr3w.png" alt=" " width="487" height="104"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now the task is to build a graph that consists of 512 nodes labeled &lt;strong&gt;0&lt;/strong&gt;, &lt;strong&gt;1&lt;/strong&gt;, &lt;strong&gt;2&lt;/strong&gt;, . . . , &lt;strong&gt;511&lt;/strong&gt;, and edges among the nodes. Once the graph is created, obtain a BFS tree rooted at node &lt;strong&gt;511&lt;/strong&gt;. From the BFS tree, you can find a shortest path from the root to any vertex. We will create a class named &lt;strong&gt;NineTailModel&lt;/strong&gt;, which contains the method to get a shortest path from the target node to any other node. The class UML diagram is shown in Figure below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcv0uvg99tkim12kqhz12.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcv0uvg99tkim12kqhz12.png" alt=" " width="756" height="275"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Visually, a node is represented in a 3 * 3 matrix with the letters &lt;strong&gt;H&lt;/strong&gt; and &lt;strong&gt;T&lt;/strong&gt;. In our program, we use a single-dimensional array of nine characters to represent a node. For example, the node for vertex &lt;strong&gt;1&lt;/strong&gt; in Figure below is represented as {&lt;strong&gt;'H'&lt;/strong&gt;, &lt;strong&gt;'H'&lt;/strong&gt;, &lt;strong&gt;'H'&lt;/strong&gt;, &lt;strong&gt;'H'&lt;/strong&gt;, &lt;strong&gt;'H'&lt;/strong&gt;, &lt;strong&gt;'H'&lt;/strong&gt;, &lt;strong&gt;'H'&lt;/strong&gt;, &lt;strong&gt;'H'&lt;/strong&gt;, &lt;strong&gt;'T'&lt;/strong&gt;} in the array.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbkhmyx0db3ez4wkcwr3w.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbkhmyx0db3ez4wkcwr3w.png" alt=" " width="487" height="104"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;getEdges()&lt;/strong&gt; method returns a list of &lt;strong&gt;Edge&lt;/strong&gt; objects.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;getNode(index)&lt;/strong&gt; method returns the node for the specified index. For example, &lt;strong&gt;getNode(0)&lt;/strong&gt; returns the node that contains nine &lt;strong&gt;H&lt;/strong&gt;s. &lt;strong&gt;getNode(511)&lt;/strong&gt; returns the node that contains nine &lt;strong&gt;T&lt;/strong&gt;s. The &lt;strong&gt;getIndex(node)&lt;/strong&gt; method returns the index of the node.&lt;/p&gt;

&lt;p&gt;Note that the data field &lt;strong&gt;tree&lt;/strong&gt; is defined as protected so that it can be accessed from the &lt;strong&gt;WeightedNineTail&lt;/strong&gt; subclass.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;getFlippedNode(char[] node, int position)&lt;/strong&gt; method flips the node at the specified position and its adjacent positions. This method returns the index of the new node.&lt;/p&gt;

&lt;p&gt;The position is a value from &lt;strong&gt;0&lt;/strong&gt; to &lt;strong&gt;8&lt;/strong&gt;, which points to a coin in the node, as shown in the following figure.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnoxz6nkr5mryz6jib32j.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnoxz6nkr5mryz6jib32j.png" alt=" " width="492" height="89"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;For example, for node &lt;strong&gt;56&lt;/strong&gt; in Figure below, flip it at position &lt;strong&gt;0&lt;/strong&gt;, and you will get node &lt;strong&gt;51&lt;/strong&gt;. If you flip node &lt;strong&gt;56&lt;/strong&gt; at position &lt;strong&gt;1&lt;/strong&gt;, you will get node &lt;strong&gt;47&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7ut3o2zebnoh7mb0n3c2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7ut3o2zebnoh7mb0n3c2.png" alt=" " width="648" height="181"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;flipACell(char[] node, int row, int column)&lt;/strong&gt; method flips a node at the specified row and column. For example, if you flip node &lt;strong&gt;56&lt;/strong&gt; at row &lt;strong&gt;0&lt;/strong&gt; and column &lt;strong&gt;0&lt;/strong&gt;, the new node is &lt;strong&gt;408&lt;/strong&gt;. If you flip node &lt;strong&gt;56&lt;/strong&gt; at row &lt;strong&gt;2&lt;/strong&gt; and column &lt;strong&gt;0&lt;/strong&gt;, the new node is &lt;strong&gt;30&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The code below shows the source code for NineTailModel.java.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import java.util.*;

public class NineTailModel {
    public final static int NUMBER_OF_NODES = 512;
    protected AbstractGraph&amp;lt;Integer&amp;gt;.Tree tree; // Define a tree

    /** Construct a model */
    public NineTailModel() {
        // Create edges
        List&amp;lt;AbstractGraph.Edge&amp;gt; edges = getEdges();

        // Create a graph
        UnweightedGraph&amp;lt;Integer&amp;gt; graph = new UnweightedGraph&amp;lt;&amp;gt;(edges, NUMBER_OF_NODES);

        // Obtain a BSF tree rooted at the target node
        tree = graph.bfs(511);
    }

    /** Create all edges for the graph */
    private List&amp;lt;AbstractGraph.Edge&amp;gt; getEdges() {
        List&amp;lt;AbstractGraph.Edge&amp;gt; edges = new ArrayList&amp;lt;&amp;gt;(); // Store edges

        for (int u = 0; u &amp;lt; NUMBER_OF_NODES; u++) {
            for (int k = 0; k &amp;lt; 9; k++) {
                char[] node = getNode(u); // Get the node for vertex u
                if (node[k] == 'H') {
                    int v = getFlippedNode(node, k);
                    // Add edge (v, u) for a legal move from node u to node v
                    edges.add(new AbstractGraph.Edge(v, u));
                }
            }
        }

        return edges;
    }

    public static int getFlippedNode(char[] node, int position) {
        int row = position / 3;
        int column = position % 3;

        flipACell(node, row, column);
        flipACell(node, row - 1, column);
        flipACell(node, row + 1, column);
        flipACell(node, row, column - 1);
        flipACell(node, row, column + 1);

        return getIndex(node);
    }

    public static void flipACell(char[] node, int row, int column) {
        if (row &amp;gt;= 0 &amp;amp;&amp;amp; row &amp;lt;= 2 &amp;amp;&amp;amp; column &amp;gt;= 0 &amp;amp;&amp;amp; column &amp;lt;= 2) {
            // Within the boundary
            if (node[row * 3 + column] == 'H')
                node[row * 3 + column] = 'T'; // Flip from H to T
            else
                node[row * 3 + column] = 'H'; // Flip from T to H
            }
    }

    public static int getIndex(char[] node) {
        int result = 0;

        for (int i = 0; i &amp;lt; 9; i++)
            if (node[i] == 'T')
                result = result * 2 + 1;
            else
                result = result * 2 + 0;

        return result;
    }

    public static char[] getNode(int index) {
        char[] result = new char[9];

        for (int i = 0; i &amp;lt; 9; i++) {
            int digit = index % 2;
            if (digit == 0)
                result[8 - i] = 'H';
            else
                result[8 - i] = 'T';
            index = index / 2;
        }

        return result;
    }

    public List&amp;lt;Integer&amp;gt; getShortestPath(int nodeIndex) {
        return tree.getPath(nodeIndex);
    }

    public static void printNode(char[] node) {
        for (int i = 0; i &amp;lt; 9; i++)
            if (i % 3 != 2)
                System.out.print(node[i]);
            else
                System.out.println(node[i]);

        System.out.println();
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The constructor (lines 8–18) creates a graph with 512 nodes, and each edge corresponds to the move from one node to the other (line 10). From the graph, a BFS tree rooted at the target node &lt;strong&gt;511&lt;/strong&gt; is obtained (line 17).&lt;/p&gt;

&lt;p&gt;To create edges, the &lt;strong&gt;getEdges&lt;/strong&gt; method (lines 21–37) checks each node &lt;strong&gt;u&lt;/strong&gt; to see if it can be flipped to another node &lt;strong&gt;v&lt;/strong&gt;. If so, add (&lt;strong&gt;v&lt;/strong&gt;, &lt;strong&gt;u&lt;/strong&gt;) to the &lt;strong&gt;Edge&lt;/strong&gt; list (line 31). The &lt;strong&gt;getFlippedNode(node, position)&lt;/strong&gt; method finds a flipped node by flipping an &lt;strong&gt;H&lt;/strong&gt; cell and its neighbors in a node (lines 43–47). The &lt;strong&gt;flipACell(node, row, column)&lt;/strong&gt; method actually flips an &lt;strong&gt;H&lt;/strong&gt; cell and its neighbors in a node (lines 52–60).&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;getIndex(node)&lt;/strong&gt; method is implemented in the same way as converting a binary number to a decimal number (lines 62–72). The &lt;strong&gt;getNode(index)&lt;/strong&gt; method returns a node consisting of the letters &lt;strong&gt;H&lt;/strong&gt; and &lt;strong&gt;T&lt;/strong&gt; (lines 74–87).&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;getShortestpath(nodeIndex)&lt;/strong&gt; method invokes the &lt;strong&gt;getPath(nodeIndex)&lt;/strong&gt;&lt;br&gt;
method to get a vertices in a shortest path from the specified node to the target node&lt;br&gt;
(lines 89–91).&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;printNode(node)&lt;/strong&gt; method displays a node on the console (lines 93–101).&lt;/p&gt;

&lt;p&gt;The code below gives a program that prompts the user to enter an initial node and displays the steps to reach the target node.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import java.util.Scanner;

public class NineTail {

    public static void main(String[] args) {
        // Prompt the user to enter nine coins' Hs and Ts
        System.out.print("Enter the initial nine coins Hs and Ts: ");
        Scanner input = new Scanner(System.in);
        String s = input.nextLine();
        char[] initialNode = s.toCharArray();

        NineTailModel model = new NineTailModel();
        java.util.List&amp;lt;Integer&amp;gt; path = model.getShortestPath(NineTailModel.getIndex(initialNode));

        System.out.println("The steps to flip the coins are ");
        for (int i = 0; i &amp;lt; path.size(); i++)
            NineTailModel.printNode(NineTailModel.getNode(path.get(i).intValue()));
    }

}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The program prompts the user to enter an initial node with nine letters with a combination of &lt;strong&gt;H&lt;/strong&gt;s and &lt;strong&gt;T&lt;/strong&gt;s as a string in line 8, obtains an array of characters from the string (line 9), creates a graph model to get a BFS tree (line 11), obtains a shortest path from the initial node to the&lt;br&gt;
target node (lines 12–13), and displays the nodes in the path (lines 16–18).&lt;/p&gt;

</description>
      <category>java</category>
      <category>programming</category>
      <category>learning</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Breadth-First Search (BFS)</title>
      <dc:creator>Paul Ike</dc:creator>
      <pubDate>Fri, 09 Aug 2024 16:17:10 +0000</pubDate>
      <link>https://dev.to/paulike/breadth-first-search-bfs-15f0</link>
      <guid>https://dev.to/paulike/breadth-first-search-bfs-15f0</guid>
      <description>&lt;p&gt;The breadth-first search of a graph visits the vertices level by level. The first level consists of the starting vertex. Each next level consists of the vertices adjacent to the vertices in the preceding level. The breadth-first traversal of a graph is like the breadth-first traversal of a tree discussed in &lt;a href="https://dev.to/paulike/binary-search-trees-5eep"&gt;Tree Traversal&lt;/a&gt;. With breadth-first traversal of a tree, the nodes are visited level by level. First the root is visited, then all the children of the root, then the grandchildren of the root, and so on. Similarly, the breadth-first search of a graph first visits a vertex, then all its adjacent vertices, then all the vertices adjacent to those vertices, and so on. To ensure that each vertex is visited only once, it skips a vertex if it has already been visited.&lt;/p&gt;

&lt;h2&gt;
  
  
  Breadth-First Search Algorithm
&lt;/h2&gt;

&lt;p&gt;The algorithm for the breadth-first search starting from vertex v in a graph is described in the code below.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Input: G = (V, E) and a starting vertex v&lt;br&gt;
 Output: a BFS tree rooted at v&lt;br&gt;
 1 Tree bfs(vertex v) {&lt;br&gt;
 2 create an empty queue for storing vertices to be visited;&lt;br&gt;
 3 add v into the queue;&lt;br&gt;
 4 mark v visited;&lt;br&gt;
 5&lt;br&gt;
 6 while (the queue is not empty) {&lt;br&gt;
 7 dequeue a vertex, say u, from the queue;&lt;br&gt;
 8 add u into a list of traversed vertices;&lt;br&gt;
 9 for each neighbor w of u&lt;br&gt;
10 if w has not been visited {&lt;br&gt;
11 add w into the queue;&lt;br&gt;
12 set u as the parent for w in the tree;&lt;br&gt;
13 mark w visited;&lt;br&gt;
14 }&lt;br&gt;
15 }&lt;br&gt;
16 }&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Consider the graph in Figure below (a). Suppose you start the breadth-first search from vertex 0. First visit 0, then visit all its neighbors, 1, 2, and 3, as shown in Figure below (b). Vertex 1 has three neighbors: 0, 2, and 4. Since 0 and 2 have already been visited, you will now visit just 4, as shown in Figure below (c). Vertex 2 has three neighbors, 0, 1, and 3, which have all been visited. Vertex 3 has three neighbors, 0, 2, and 4, which have all been visited. Vertex 4 has two neighbors, 1 and 3, which have all been visited. Hence, the search ends.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2p6xo8wts0cyrz1lukgg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2p6xo8wts0cyrz1lukgg.png" alt=" " width="648" height="181"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Since each edge and each vertex is visited only once, the time complexity of the &lt;strong&gt;bfs&lt;/strong&gt; method is &lt;strong&gt;O(|E| + |V|)&lt;/strong&gt;, where &lt;strong&gt;|E|&lt;/strong&gt; denotes the number of edges and &lt;strong&gt;|V|&lt;/strong&gt; the number of vertices.&lt;/p&gt;
&lt;h2&gt;
  
  
  Implementation of Breadth-First Search
&lt;/h2&gt;

&lt;p&gt;The &lt;strong&gt;bfs(int v)&lt;/strong&gt; method is defined in the &lt;strong&gt;Graph&lt;/strong&gt; interface and implemented in the &lt;a href="https://dev.to/paulike/modeling-graphs-5d01"&gt;AbstractGraph.java&lt;/a&gt; class (lines 197–222). It returns an instance of the &lt;strong&gt;Tree&lt;/strong&gt; class with vertex v as the root. The method stores the vertices searched in the list &lt;strong&gt;searchOrder&lt;/strong&gt; (line 198), the parent of each vertex in the array &lt;strong&gt;parent&lt;/strong&gt; (line 199), uses a linked list for a queue (lines 203–204), and uses the &lt;strong&gt;isVisited&lt;/strong&gt; array to indicate whether a vertex has been visited (line 207). The search starts from vertex &lt;strong&gt;v&lt;/strong&gt;. &lt;strong&gt;v&lt;/strong&gt; is added to the queue in line 206 and is marked as visited (line 207). The method now examines each vertex &lt;strong&gt;u&lt;/strong&gt; in the queue (line 210) and adds it to &lt;strong&gt;searchOrder&lt;/strong&gt; (line 211). The method adds each unvisited neighbor &lt;strong&gt;e.v&lt;/strong&gt; of &lt;strong&gt;u&lt;/strong&gt; to the queue (line 214), sets its parent to &lt;strong&gt;u&lt;/strong&gt; (line 215), and marks it as visited (line 216).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3m0o6sbkp41nt81s1ie7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3m0o6sbkp41nt81s1ie7.png" alt=" " width="757" height="332"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The code below gives a test program that displays a BFS for the graph in Figure above starting from Chicago.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class TestBFS {

    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}, {0, 3}, {0, 5},
                {1, 0}, {1, 2}, {1, 3},
                {2, 1}, {2, 3}, {2, 4}, {2, 10},
                {3, 0}, {3, 1}, {3, 2}, {3, 4}, {3, 5},
                {4, 2}, {4, 3}, {4, 5}, {4, 7}, {4, 8}, {4, 10},
                {5, 0}, {5, 3}, {5, 4}, {5, 6}, {5, 7},
                {6, 5}, {6, 7},
                {7, 4}, {7, 5}, {7, 6}, {7, 8},
                {8, 4}, {8, 7}, {8, 9}, {8, 10}, {8, 11},
                {9, 8}, {9, 11},
                {10, 2}, {10, 4}, {10, 8}, {10, 11},
                {11, 8}, {11, 9}, {11, 10}
        };

        Graph&amp;lt;String&amp;gt; graph = new UnweightedGraph&amp;lt;&amp;gt;(vertices, edges);
        AbstractGraph&amp;lt;String&amp;gt;.Tree bfs = graph.bfs(graph.getIndex("Chicago"));

        java.util.List&amp;lt;Integer&amp;gt; searchOrders = bfs.getSearchOrder();
        System.out.println(bfs.getNumberOfVerticesFound() + " vertices are searched in this BFS order:");
        for(int i = 0; i &amp;lt; searchOrders.size(); i++)
            System.out.print(graph.getVertex(searchOrders.get(i)) + " ");
        System.out.println();

        for(int i = 0; i &amp;lt; searchOrders.size(); i++)
            if(bfs.getParent(i) != -1)
                System.out.println("parent of " + graph.getVertex(i) + " is " + graph.getVertex(bfs.getParent(i)));
    }

}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;12 vertices are searched in this order:&lt;br&gt;
 Chicago Seattle Denver Kansas City Boston New York&lt;br&gt;
 San Francisco Los Angeles Atlanta Dallas Miami Houston&lt;br&gt;
parent of Seattle is Chicago&lt;br&gt;
parent of San Francisco is Seattle&lt;br&gt;
parent of Los Angeles is Denver&lt;br&gt;
parent of Denver is Chicago&lt;br&gt;
parent of Kansas City is Chicago&lt;br&gt;
parent of Boston is Chicago&lt;br&gt;
parent of New York is Chicago&lt;br&gt;
parent of Atlanta is Kansas City&lt;br&gt;
parent of Miami is Atlanta&lt;br&gt;
parent of Dallas is Kansas City&lt;br&gt;
parent of Houston is Atlanta&lt;/code&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Applications of the BFS
&lt;/h2&gt;

&lt;p&gt;Many of the problems solved by the DFS can also be solved using the BFS. Specifically, the BFS can be used to solve the following problems:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Detecting whether a graph is connected. A graph is connected if there is a path between any two vertices in the graph.&lt;/li&gt;
&lt;li&gt;Detecting whether there is a path between two vertices.&lt;/li&gt;
&lt;li&gt;Finding a shortest path between two vertices. You can prove that the path between the root and any node in the BFS tree is a shortest path between the root and the node.&lt;/li&gt;
&lt;li&gt;Finding all connected components. A connected component is a maximal connected subgraph in which every pair of vertices are connected by a path.&lt;/li&gt;
&lt;li&gt;Detecting whether there is a cycle in the graph.&lt;/li&gt;
&lt;li&gt;Finding a cycle in the graph.&lt;/li&gt;
&lt;li&gt;Testing whether a graph is bipartite. (A graph is bipartite if the vertices of the graph can be divided into two disjoint sets such that no edges exist between vertices in the same set.)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1kvduik5g5k08wuqm0b4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1kvduik5g5k08wuqm0b4.png" alt=" " width="751" height="504"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>java</category>
      <category>programming</category>
      <category>learning</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Case Study: The Connected Circles Problem</title>
      <dc:creator>Paul Ike</dc:creator>
      <pubDate>Fri, 09 Aug 2024 15:40:45 +0000</pubDate>
      <link>https://dev.to/paulike/case-study-the-connected-circles-problem-4in9</link>
      <guid>https://dev.to/paulike/case-study-the-connected-circles-problem-4in9</guid>
      <description>&lt;p&gt;The connected circles problem is to determine whether all circles in a two-dimensional plane are connected. This problem can be solved using a depth-first traversal. The DFS algorithm has many applications. This section applies the DFS algorithm to solve the connected circles problem.&lt;/p&gt;

&lt;p&gt;In the connected circles problem, you determine whether all the circles in a two-dimensional plane are connected. If all the circles are connected, they are painted as filled circles, as shown in Figure below (a). Otherwise, they are not filled, as shown in Figure below (b).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7sfh9f5rp0h8yjdjmbqs.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7sfh9f5rp0h8yjdjmbqs.png" alt=" " width="649" height="244"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We will write a program that lets the user create a circle by clicking a mouse in a blank area that is not currently covered by a circle. As the circles are added, the circles are repainted filled if they are connected or unfilled otherwise.&lt;/p&gt;

&lt;p&gt;We will create a graph to model the problem. Each circle is a vertex in the graph. Two circles are connected if they overlap. We apply the DFS in the graph, and if all vertices are found in the depth-first search, the graph is connected.&lt;/p&gt;

&lt;p&gt;The program is given in the code below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import javafx.application.Application;
import javafx.geometry.Point2D;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;

public class ConnectedCircles extends Application {
    @Override // Override the start method in the Application class
    public void start(Stage primaryStage) {
        // Create a scene and place it in the stage
        Scene scene = new Scene(new CirclePane(), 450, 350);
        primaryStage.setTitle("ConnectedCircles"); // Set the stage title
        primaryStage.setScene(scene); // Place the scene in the stage
        primaryStage.show(); // Display the stage
    }

    public static void main(String[] args) {
        Application.launch(args);
    }

    /** Pane for displaying circles */
    class CirclePane extends Pane {
        public CirclePane() {
            this.setOnMouseClicked(e -&amp;gt; {
                if (!isInsideACircle(new Point2D(e.getX(), e.getY()))) {
                    // Add a new circle
                    getChildren().add(new Circle(e.getX(), e.getY(), 20));
                    colorIfConnected();
                }
            });
        }

        /** Returns true if the point is inside an existing circle */
        private boolean isInsideACircle(Point2D p) {
            for (Node circle: this.getChildren())
                if (circle.contains(p))
                    return true;

            return false;
        }

        /** Color all circles if they are connected */
        private void colorIfConnected() {
            if (getChildren().size() == 0)
                return; // No circles in the pane

            // Build the edges
            java.util.List&amp;lt;AbstractGraph.Edge&amp;gt; edges = new java.util.ArrayList&amp;lt;&amp;gt;();
            for (int i = 0; i &amp;lt; getChildren().size(); i++)
                for (int j = i + 1; j &amp;lt; getChildren().size(); j++)
                    if (overlaps((Circle)(getChildren().get(i)), (Circle)(getChildren().get(j)))) {
                        edges.add(new AbstractGraph.Edge(i, j));
                        edges.add(new AbstractGraph.Edge(j, i));
                    }

            // Create a graph with circles as vertices
            Graph&amp;lt;Node&amp;gt; graph = new UnweightedGraph&amp;lt;&amp;gt;((java.util.List&amp;lt;Node&amp;gt;)getChildren(), edges);
            AbstractGraph&amp;lt;Node&amp;gt;.Tree tree = graph.dfs(0); // a DFS tree
            boolean isAllCirclesConnected = getChildren().size() == tree.getNumberOfVerticesFound();

            for (Node circle: getChildren()) {
                if (isAllCirclesConnected) { // All circles are connected
                    ((Circle)circle).setFill(Color.RED);
                }
                else {
                    ((Circle)circle).setStroke(Color.BLACK);
                    ((Circle)circle).setFill(Color.WHITE);
                }
            }
        }
    }

    public static boolean overlaps(Circle circle1, Circle circle2) {
        return new Point2D(circle1.getCenterX(), circle1.getCenterY()).distance(circle2.getCenterX(), circle2.getCenterY()) &amp;lt;= circle1.getRadius() + circle2.getRadius();
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The JavaFX &lt;strong&gt;Circle&lt;/strong&gt; class contains the data fields &lt;strong&gt;x&lt;/strong&gt;, &lt;strong&gt;y&lt;/strong&gt;, and &lt;strong&gt;radius&lt;/strong&gt;, which specify the circle’s center location and radius. It also defines the &lt;strong&gt;contains&lt;/strong&gt; for testing if a point is in the circle. The &lt;strong&gt;overlaps&lt;/strong&gt; method (lines 76–80) checks whether two circles overlap.&lt;/p&gt;

&lt;p&gt;When the user clicks the mouse outside of any existing circle, a new circle is created centered at the mouse point and the circle is added to the pane (line 26).&lt;/p&gt;

&lt;p&gt;To detect whether the circles are connected, the program constructs a graph (lines 46–59). The circles are the vertices of the graph. The edges are constructed in lines 49–55. Two circle vertices are connected if they overlap (line 51). The DFS of the graph results in a tree (line 60). The tree’s &lt;strong&gt;getNumberOfVerticesFound()&lt;/strong&gt; returns the number of vertices searched. If it is equal to the number of circles, all circles are connected (lines 61–62).&lt;/p&gt;

</description>
      <category>java</category>
      <category>programming</category>
      <category>learning</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Depth-First Search (DFS)</title>
      <dc:creator>Paul Ike</dc:creator>
      <pubDate>Fri, 09 Aug 2024 15:30:42 +0000</pubDate>
      <link>https://dev.to/paulike/depth-first-search-dfs-4gid</link>
      <guid>https://dev.to/paulike/depth-first-search-dfs-4gid</guid>
      <description>&lt;p&gt;The depth-first search of a graph starts from a vertex in the graph and visits all vertices in the graph as far as possible before backtracking.&lt;br&gt;
The depth-first search of a graph is like the depth-first search of a tree discussed in &lt;a href="https://dev.to/paulike/binary-search-trees-5eep"&gt;Tree Traversal&lt;/a&gt;, Tree Traversal. In the case of a tree, the search starts from the root. In a graph, the search can start from any vertex.&lt;/p&gt;

&lt;p&gt;A depth-first search of a tree first visits the root, then recursively visits the subtrees of the root. Similarly, the depth-first search of a graph first visits a vertex, then it recursively visits all the vertices adjacent to that vertex. The difference is that the graph may contain cycles, which could lead to an infinite recursion. To avoid this problem, you need to track the vertices that have already been visited.&lt;/p&gt;

&lt;p&gt;The search is called &lt;em&gt;depth-first&lt;/em&gt; because it searches “deeper” in the graph as much as possible. The search starts from some vertex v. After visiting v, it visits an unvisited neighbor of v. If v has no unvisited neighbor, the search backtracks to the vertex from which it reached v. We assume that the graph is connected and the search starting from any vertex can reach all the vertices.&lt;/p&gt;
&lt;h2&gt;
  
  
  Depth-First Search Algorithm
&lt;/h2&gt;

&lt;p&gt;The algorithm for the depth-first search is described in the code below.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Input: G = (V, E) and a starting vertex v&lt;br&gt;
 Output: a DFS tree rooted at v&lt;br&gt;
 1 Tree dfs(vertex v) {&lt;br&gt;
 2 visit v; &lt;br&gt;
 3 for each neighbor w of v&lt;br&gt;
 4 if (w has not been visited) {&lt;br&gt;
 5 set v as the parent for w in the tree;&lt;br&gt;
 6 dfs(w);&lt;br&gt;
 7 }&lt;br&gt;
 8 }&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;You can use an array named &lt;strong&gt;isVisited&lt;/strong&gt; to denote whether a vertex has been visited. Initially, &lt;strong&gt;isVisited[i]&lt;/strong&gt; is &lt;strong&gt;false&lt;/strong&gt; for each vertex i. Once a vertex, say v, is visited, &lt;strong&gt;isVisited[v]&lt;/strong&gt; is set to &lt;strong&gt;true&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Consider the graph in Figure below (a). Suppose we start the depth-first search from vertex 0. First visit 0, then any of its neighbors, say 1. Now 1 is visited, as shown in Figure below (b). Vertex 1 has three neighbors—0, 2, and 4. Since 0 has already been visited, you will visit either 2 or 4. Let us pick 2. Now 2 is visited, as shown in Figure below (c). Vertex 2 has three neighbors: 0, 1, and 3. Since 0 and 1 have already been visited, pick 3. 3 is now visited, as shown in Figure below (d). At this point, the vertices have been visited in this order:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;0&lt;/strong&gt;, &lt;strong&gt;1&lt;/strong&gt;, &lt;strong&gt;2&lt;/strong&gt;, &lt;strong&gt;3&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Since all the neighbors of 3 have been visited, backtrack to 2. Since all the vertices of 2 have been visited, backtrack to 1. 4 is adjacent to 1, but 4 has not been visited. Therefore, visit 4, as shown in Figure below (e). Since all the neighbors of 4 have been visited, backtrack to 1.&lt;br&gt;
Since all the neighbors of 1 have been visited, backtrack to 0. Since all the neighbors of 0 have been visited, the search ends.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzgumagfvrp5x9odzb33v.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzgumagfvrp5x9odzb33v.png" alt=" " width="494" height="345"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Since each edge and each vertex is visited only once, the time complexity of the &lt;strong&gt;dfs&lt;/strong&gt; method is &lt;strong&gt;O(|E| + |V|)&lt;/strong&gt;, where &lt;strong&gt;|E|&lt;/strong&gt; denotes the number of edges and &lt;strong&gt;|V|&lt;/strong&gt; the number of vertices.&lt;/p&gt;
&lt;h2&gt;
  
  
  Implementation of Depth-First Search
&lt;/h2&gt;

&lt;p&gt;The algorithm for DFS in the code above uses recursion. It is natural to use recursion to implement it. Alternatively, you can use a stack.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;dfs(int v)&lt;/strong&gt; method is implemented in lines 164–193 in &lt;a href="https://dev.to/paulike/modeling-graphs-5d01"&gt;AbstractGraph.java&lt;/a&gt;. It returns an instance of the &lt;strong&gt;Tree&lt;/strong&gt; class with vertex &lt;strong&gt;v&lt;/strong&gt; as the root. The method stores the vertices searched in the list &lt;strong&gt;searchOrder&lt;/strong&gt; (line 165), the parent of each vertex in the array &lt;strong&gt;parent&lt;/strong&gt; (line 166), and uses the &lt;strong&gt;isVisited&lt;/strong&gt; array to indicate whether a vertex has been visited (line 171). It invokes the helper method &lt;strong&gt;dfs(v, parent, searchOrder, isVisited)&lt;/strong&gt; to perform a depth-first search (line 174).&lt;/p&gt;

&lt;p&gt;In the recursive helper method, the search starts from vertex &lt;strong&gt;u&lt;/strong&gt;. &lt;strong&gt;u&lt;/strong&gt; is added to &lt;strong&gt;searchOrder&lt;/strong&gt; in line 184 and is marked as visited (line 185). For each unvisited neighbor of &lt;strong&gt;u&lt;/strong&gt;, the method is recursively invoked to perform a depth-first search. When a vertex &lt;strong&gt;e.v&lt;/strong&gt; is visited, the parent of &lt;strong&gt;e.v&lt;/strong&gt; is stored in &lt;strong&gt;parent[e.v]&lt;/strong&gt; (line 189). The method returns when all vertices are visited for a connected graph, or in a connected component.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6oz3ugxx6u02ht3t662a.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6oz3ugxx6u02ht3t662a.png" alt=" " width="757" height="332"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The code below gives a test program that displays a DFS for the graph in Figure above starting from Chicago. The graphical illustration of the DFS starting from Chicago is shown in Figure below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class TestDFS {

    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}, {0, 3}, {0, 5},
                {1, 0}, {1, 2}, {1, 3},
                {2, 1}, {2, 3}, {2, 4}, {2, 10},
                {3, 0}, {3, 1}, {3, 2}, {3, 4}, {3, 5},
                {4, 2}, {4, 3}, {4, 5}, {4, 7}, {4, 8}, {4, 10},
                {5, 0}, {5, 3}, {5, 4}, {5, 6}, {5, 7},
                {6, 5}, {6, 7},
                {7, 4}, {7, 5}, {7, 6}, {7, 8},
                {8, 4}, {8, 7}, {8, 9}, {8, 10}, {8, 11},
                {9, 8}, {9, 11},
                {10, 2}, {10, 4}, {10, 8}, {10, 11},
                {11, 8}, {11, 9}, {11, 10}
        };

        Graph&amp;lt;String&amp;gt; graph = new UnweightedGraph&amp;lt;&amp;gt;(vertices, edges);
        AbstractGraph&amp;lt;String&amp;gt;.Tree dfs = graph.dfs(graph.getIndex("Chicago"));

        java.util.List&amp;lt;Integer&amp;gt; searchOrders = dfs.getSearchOrder();
        System.out.println(dfs.getNumberOfVerticesFound() + " vertices are searched in this DFS order:");
        for(int i = 0; i &amp;lt; searchOrders.size(); i++)
            System.out.print(graph.getVertex(searchOrders.get(i)) + " ");
        System.out.println();

        for(int i = 0; i &amp;lt; searchOrders.size(); i++)
            if(dfs.getParent(i) != -1)
                System.out.println("parent of " + graph.getVertex(i) + " is " + graph.getVertex(dfs.getParent(i)));
    }

}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;12 vertices are searched in this DFS order:&lt;br&gt;
 Chicago Seattle San Francisco Los Angeles Denver&lt;br&gt;
 Kansas City New York Boston Atlanta Miami Houston Dallas&lt;br&gt;
parent of Seattle is Chicago&lt;br&gt;
parent of San Francisco is Seattle&lt;br&gt;
parent of Los Angeles is San Francisco&lt;br&gt;
parent of Denver is Los Angeles&lt;br&gt;
parent of Kansas City is Denver&lt;br&gt;
parent of Boston is New York&lt;br&gt;
parent of New York is Kansas City&lt;br&gt;
parent of Atlanta is New York&lt;br&gt;
parent of Miami is Atlanta&lt;br&gt;
parent of Dallas is Houston&lt;br&gt;
parent of Houston is Miami&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fujpeemrawf6oxzr2xizu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fujpeemrawf6oxzr2xizu.png" alt=" " width="751" height="497"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Applications of the DFS
&lt;/h2&gt;

&lt;p&gt;The depth-first search can be used to solve many problems, such as the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Detecting whether a graph is connected. Search the graph starting from any vertex. If the number of vertices searched is the same as the number of vertices in the graph, the graph is connected. Otherwise, the graph is not connected.&lt;/li&gt;
&lt;li&gt;Detecting whether there is a path between two vertices.&lt;/li&gt;
&lt;li&gt;Finding a path between two vertices.&lt;/li&gt;
&lt;li&gt;Finding all connected components. A connected component is a maximal connected subgraph in which every pair of vertices are connected by a path.&lt;/li&gt;
&lt;li&gt;Detecting whether there is a cycle in the graph.&lt;/li&gt;
&lt;li&gt;Finding a cycle in the graph.&lt;/li&gt;
&lt;li&gt;Finding a Hamiltonian path/cycle. A &lt;em&gt;Hamiltonian path&lt;/em&gt; in a graph is a path that visits each vertex in the graph exactly once. A &lt;em&gt;Hamiltonian cycle&lt;/em&gt; visits each vertex in the graph exactly once and returns to the starting vertex.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The first six problems can be easily solved using the dfs method in &lt;a href="https://dev.to/paulike/modeling-graphs-5d01"&gt;AbstractGraph.java&lt;/a&gt;. To find a Hamiltonian path/cycle, you have to explore all possible DFSs to find the one that leads to the longest path. The Hamiltonian path/cycle has many applications, including for solving the well-known Knight’s Tour problem.&lt;/p&gt;

</description>
      <category>java</category>
      <category>programming</category>
      <category>learning</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Graph Traversals</title>
      <dc:creator>Paul Ike</dc:creator>
      <pubDate>Fri, 09 Aug 2024 15:05:46 +0000</pubDate>
      <link>https://dev.to/paulike/graph-traversals-2jg9</link>
      <guid>https://dev.to/paulike/graph-traversals-2jg9</guid>
      <description>&lt;p&gt;Depth-first and breadth-first are two common ways to traverse a graph.&lt;br&gt;
&lt;em&gt;Graph traversal&lt;/em&gt; is the process of visiting each vertex in the graph exactly once. There are two popular ways to traverse a graph: &lt;em&gt;depth-first traversal&lt;/em&gt; (or &lt;em&gt;depth-first search&lt;/em&gt;) and &lt;em&gt;breadth-first traversal&lt;/em&gt; (or &lt;em&gt;breadth-first search&lt;/em&gt;). Both traversals result in a spanning tree, which can be modeled using a class, as shown in Figure below. Note that &lt;strong&gt;Tree&lt;/strong&gt; is an inner class defined in the &lt;strong&gt;AbstractGraph&lt;/strong&gt; class. &lt;strong&gt;AbstractGraph.Tree&lt;/strong&gt; is different from the &lt;strong&gt;Tree&lt;/strong&gt; interface defined in &lt;a href="https://dev.to/paulike/binary-search-trees-5eep"&gt;Searching for an Element&lt;/a&gt;. &lt;strong&gt;AbstractGraph.Tree&lt;/strong&gt; is a specialized class designed for describing the parent–child relationship of the nodes, whereas the &lt;strong&gt;Tree&lt;/strong&gt; interface defines common operations such as searching, inserting, and deleting in a tree. Since there is no need to perform these operations for a spanning tree, &lt;strong&gt;AbstractGraph.Tree&lt;/strong&gt; is not defined as a subtype of &lt;strong&gt;Tree&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe87aiptutxwapnifolqb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe87aiptutxwapnifolqb.png" alt=" " width="757" height="266"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;Tree&lt;/strong&gt; class is defined as an inner class in the &lt;strong&gt;AbstractGraph&lt;/strong&gt; class in lines 226–293 in &lt;a href="https://dev.to/paulike/modeling-graphs-5d01"&gt;AbstractGraph.java&lt;/a&gt;. The constructor creates a tree with the root, edges, and a search order.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;Tree&lt;/strong&gt; class defines seven methods. The &lt;strong&gt;getRoot()&lt;/strong&gt; method returns the root of the tree. You can get the order of the vertices searched by invoking the &lt;strong&gt;getSearchOrder()&lt;/strong&gt; method. You can invoke &lt;strong&gt;getParent(v)&lt;/strong&gt; to find the parent of vertex &lt;strong&gt;v&lt;/strong&gt; in the search. Invoking &lt;strong&gt;getNumberOfVerticesFound()&lt;/strong&gt; returns the number of vertices searched. The method &lt;strong&gt;getPath(index)&lt;/strong&gt; returns a list of vertices from the specified vertex index to the root. Invoking &lt;strong&gt;printPath(v)&lt;/strong&gt; displays a path from the root to &lt;strong&gt;v&lt;/strong&gt;. You can display all edges in the tree using the &lt;strong&gt;printTree()&lt;/strong&gt; method.&lt;/p&gt;

</description>
      <category>java</category>
      <category>programming</category>
      <category>learning</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Graph Visualization</title>
      <dc:creator>Paul Ike</dc:creator>
      <pubDate>Fri, 09 Aug 2024 14:52:17 +0000</pubDate>
      <link>https://dev.to/paulike/graph-visualization-3p9l</link>
      <guid>https://dev.to/paulike/graph-visualization-3p9l</guid>
      <description>&lt;p&gt;To display a graph visually, each vertex must be assigned a location. The preceding section introduced how to model a graph using the &lt;strong&gt;Graph&lt;/strong&gt; interface, &lt;strong&gt;AbstractGraph&lt;/strong&gt; class, and &lt;strong&gt;UnweightedGraph&lt;/strong&gt; class. This section discusses how to display graphs graphically. In order to display a graph, you need to know where each vertex is displayed and the name of each vertex. To ensure a graph can be displayed, we define an interface named &lt;strong&gt;Displayable&lt;/strong&gt; that has the methods for obtaining the &lt;strong&gt;x-&lt;/strong&gt; and &lt;strong&gt;y-&lt;/strong&gt;coordinates and their names, and make vertices instances of &lt;strong&gt;Displayable&lt;/strong&gt;, in the code below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc3xufbazyqcbmlyr37zm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc3xufbazyqcbmlyr37zm.png" alt=" " width="682" height="317"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A graph with &lt;strong&gt;Displayable&lt;/strong&gt; vertices can now be displayed on a pane named &lt;strong&gt;GraphView&lt;/strong&gt;, as shown in the code below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpp9e4vja6u8jfnjp9m9a.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpp9e4vja6u8jfnjp9m9a.png" alt=" " width="800" height="675"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To display a graph on a pane, simply create an instance of &lt;strong&gt;GraphView&lt;/strong&gt; by passing the graph as an argument in the constructor (line 9). The class for the graph’s vertex must implement the &lt;strong&gt;Displayable&lt;/strong&gt; interface in order to display the vertices (lines 13–22). For each vertex index &lt;strong&gt;i&lt;/strong&gt;, invoking &lt;strong&gt;graph.getNeighbors(i)&lt;/strong&gt; returns its adjacency list (line 26). From this list, you can find all vertices that are adjacent to &lt;strong&gt;i&lt;/strong&gt; and draw a line to connect &lt;strong&gt;i&lt;/strong&gt; with its adjacent vertex (lines 27–34).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fr1xmxqnvfvd8arosufwu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fr1xmxqnvfvd8arosufwu.png" alt=" " width="757" height="332"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The code below gives an example of displaying the graph in Figure above, as shown in Figure below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fa1385hoyro3cooabosk8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fa1385hoyro3cooabosk8.png" alt=" " width="494" height="275"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class DisplayUSMap extends Application {
    @Override // Override the start method in the Application class
    public void start(Stage primaryStage) {
        City[] vertices = {new City("Seattle", 75, 50),
                new City("San Francisco", 50, 210),
                new City("Los Angeles", 75, 275), new City("Denver", 275, 175),
                new City("Kansas City", 400, 245),
                new City("Chicago", 450, 100), new City("Boston", 700, 80),
                new City("New York", 675, 120), new City("Atlanta", 575, 295),
                new City("Miami", 600, 400), new City("Dallas", 408, 325),
                new City("Houston", 450, 360)};

        // Edge array for graph
        int[][] edges = {
                {0, 1}, {0, 3}, {0, 5}, {1, 0}, {1, 2}, {1, 3},
                {2, 1}, {2, 3}, {2, 4}, {2, 10},
                {3, 0}, {3, 1}, {3, 2}, {3, 4}, {3, 5},
                {4, 2}, {4, 3}, {4, 5}, {4, 7}, {4, 8}, {4, 10},
                {5, 0}, {5, 3}, {5, 4}, {5, 6}, {5, 7},
                {6, 5}, {6, 7}, {7, 4}, {7, 5}, {7, 6}, {7, 8},
                {8, 4}, {8, 7}, {8, 9}, {8, 10}, {8, 11},
                {9, 8}, {9, 11}, {10, 2}, {10, 4}, {10, 8}, {10, 11},
                {11, 8}, {11, 9}, {11, 10}
        };

        Graph&amp;lt;City&amp;gt; graph = new UnweightedGraph&amp;lt;&amp;gt;(vertices, edges);

        // Create a scene and place it in the stage
        Scene scene = new Scene(new GraphView(graph), 750, 450);
        primaryStage.setTitle("DisplayUSMap"); // Set the stage title
        primaryStage.setScene(scene); // Place the scene in the stage
        primaryStage.show(); // Display the stage
    }

    public static void main(String[] args) {
        Application.launch(args);
    }

    static class City implements Displayable {
        private int x, y;
        private String name;

        City(String name, int x, int y) {
            this.name = name;
            this.x = x;
            this.y = y;
        }

        @Override
        public int getX() {
            return x;
        }

        @Override
        public int getY() {
            return y;
        }

        @Override
        public String getName() {
            return name;
        }
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The class &lt;strong&gt;City&lt;/strong&gt; is defined to model the vertices with their coordinates and names (lines 39–63). The program creates a graph with the vertices of the &lt;strong&gt;City&lt;/strong&gt; type (line 30). Since &lt;strong&gt;City&lt;/strong&gt; implements &lt;strong&gt;Displayable&lt;/strong&gt;, a &lt;strong&gt;GraphView&lt;/strong&gt; object created for the graph displays the graph in the pane (line 33).&lt;/p&gt;

</description>
      <category>java</category>
      <category>programming</category>
      <category>learning</category>
      <category>beginners</category>
    </item>
  </channel>
</rss>
