【发布时间】:2019-09-10 19:25:37
【问题描述】:
我正在处理 Java 编码挑战,我的驱动程序从文本文件中读取城市名称和城市之间的里程数。然后,此信息将传递给将填充加权无向图的方法。城市名称是节点,它们之间的里程是权重。我正在编写 Graph 类,并且我正在为邻接矩阵使用 Linked List 数据类型。
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);
}
}
在我正在使用的示例中,节点是编号的,而不是命名的,变量“origin”和“destination”是整数。有人建议我需要获取字符串的索引值并在行中使用它们:
adjList[origin].add(edge);
adjList[destination].add(edge);
在 addUndirectedEdge 方法中。我怎么做? 我需要将变量“origin”和“domain”声明为整数而不是字符串吗?
【问题讨论】:
-
您只能使用整数对链表进行索引,但您正尝试使用字符串进行索引。您需要找到该字符串所在的索引,然后使用它。
-
我该怎么做?在我正在处理的示例中,节点编号未命名,因此更容易。
-
是否需要使用 LinkedList
?对于列出的要求, Map > (Map >) 是否可行? -
我不熟悉地图。
标签: java linked-list undirected-graph weighted-graph