在创建顶点并在定向图中使用它们时遇到一些麻烦。
我有两个要关注的类:Node.java和Digraph.java
public class Node {
private final int vertex;
private HashSet<Node> outgoingEdges;
public Node(int index) {
this.index = index;
}
protected void addOutgoing(Node start) {
outgoingEdges.add(start);
}
public class Digraph {
private Set<Node> vertices;
public Digraph(String str) {
String eliminatePrefix = str.replaceAll("a", "");
for (int i = 0; i < eliminatePrefix.length; i++) {
// Not sure how to proceed
//
}
protected void add(Node a, Node b) {
a.addOutgoing(b);
}
传入的字符串看起来像[a1,a2] [a16,a10] .... a1和a2是顶点。配对意味着有从a1到a2的有向路线。我知道,字符串需要被解析和转换,一旦格式正确,就会调用addEdge方法。我只想弄清楚这个构造函数。
答案 0 :(得分:0)
也许不是最干净的方法,但它有效
String s = "[a1, a2][a3, a4][a5, a6]";
s = s.replaceAll("[a\\s\\[]", ""); // remove " " "[" and ","
String[] edges = s.split("]"); // split the string into substrings on ]
for (String edge : edges) {
String[] points = edge.split(",");
int[] p = new int[2];
p[0] = Integer.parseInt(points[0]);
p[1] = Integer.parseInt(points[1]);
// Construct your edge here
System.out.println("Edge from: " + p[0] + " to " + p[1]);
}