简体   繁体   English

如何在 Java 的广度优先搜索中将字符串顶点转换为 Integer 顶点

[英]How can i convert String Vertex to Integer vertex in Breadth First Search in Java

I'm trying to get data from a txt file and create a graph.我正在尝试从 txt 文件中获取数据并创建图表。 But I can't do this because vertex1 and vertex2 are String values.但我不能这样做,因为 vertex1 和 vertex2 是字符串值。

for example例如

Vertex1 - Vertex2 - Edges顶点 1 - 顶点 2 - 边

John Lisa 4...约翰丽莎 4...

As I understand it, in order to write this Breadth First Search method, I need to save the String values in a hash table but I can't because I need integer values.据我了解,为了编写这种广度优先搜索方法,我需要将字符串值保存在 hash 表中,但我不能,因为我需要 integer 值。 How can I do it?我该怎么做?

Meant is mapping names to a counter.意思是将名称映射到计数器。

private final Map<String, Integer> vertexIdsByName = new HashMap<>();

public int getVertexId(String name) {
    return vertexIdsByName.computeIfAbsent(name,
            nm -> vertexIdsByName.size() + 1);
}

The above translates vertex names to an integer ID, 1, 2, 3, ...以上将顶点名称转换为 integer ID, 1, 2, 3, ...

If the asked vertex name already is present, its ID is returned, otherwise a new ID, the number of elements in the HashMap + 1 is stored as the new ID and returned.如果请求的顶点名称已经存在,则返回其 ID,否则返回新 ID,将 HashMap + 1 中的元素数存储为新 ID 并返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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