简体   繁体   中英

Building a Weighted Undirected Graph

I'm working on a coding challenge in Java where my driver reads in the names of cities and the mileages between them from text files. This information is then going to be passed to a method which will populate a weighted, undirected graph. The city names are the nodes and the mileages between them are the weights. I am writing the Graph class, and I'm using a Linked List data type for the adjacency matrix.

import java.util.LinkedList;

public class WeightedGraph {

    static class Edge
    {
        String origin;
        String destination;
        int weight;

        public Edge(String origin, String destination, int weight)
        {
            this.origin = origin;
            this.destination = destination;
            this.weight = weight;
        }
    }

    static class Graph
    {
        int numVertices;
        LinkedList<Edge>[] adjList;

        Graph(int numVertices)
        {
            this.numVertices = numVertices;
            adjList = new LinkedList[numVertices];

            for(int i = 0; i < numVertices; i++)
            {
                adjList[i] = new LinkedList<>();
            }
        }

    }

    public void addUndirectedEdge(String origin, String destination, int weight)
    {
        Edge edge = new Edge(origin, destination, weight);
        adjList[origin].add(edge);
        adjList[destination].add(edge);
    }
}

In the example I'm working from, the nodes are numbered, not named, and the variables "origin" and "destination" are integers. It was proposed that I need to get the index values for the strings and use those in the lines:

        adjList[origin].add(edge);
        adjList[destination].add(edge);

which are in the addUndirectedEdge method. How do I do that? Do I need to declare the variables "origin" and "domain" as integers instead of strings?

    adjList[origin].add(edge);
    adjList[destination].add(edge);

Origin and destination are string here. And you are trying to get array item by string.

In the language of your IDE:

Expected: adjList[int]

Found: adjList[String]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM