gpt4 book ai didi

java - 计算图中所有顶点的数量

转载 作者:行者123 更新时间:2023-12-02 00:07:00 42 4
gpt4 key购买 nike

我对java相当陌生,我已经为这个练习苦苦挣扎了两周(这是我学校的家庭作业)。我需要创建一个拓扑排序并打印出所有可能的连接。我现在已经阅读了很多有关拓扑排序的内容,但是我们必须使用这行代码。我很确定当我有顶点列表时我可以进行拓扑排序。我的问题是,我不知道如何列出给定代码中的所有顶点。任何人都可以给我一些提示或线索,或者也许是一个例子,我真的非常感激。

这是我们需要使用的给定代码:

import java.util.*;

public class Answer {

public static void main (String[] args) {
Answer a = new Answer();
a.run();
}

public void run() {

// TODO!!! YOUR TESTS HERE!

Graph g = new Graph ("G");
Vertex a = new Vertex ("A");
Vertex b = new Vertex ("B");
Vertex c = new Vertex ("C");
g.first = a;
a.next = b;
b.next = c;
Edge ab = new Edge ("AB");
Edge ac = new Edge ("AC");
Edge ba = new Edge ("BA");
Edge ca = new Edge ("CA");
a.first = ab;
b.first = ba;
c.first = ca;
ab.next = ac;
ab.target = b;
ac.target = c;
ba.target = a;
ca.target = a;
System.out.println (g);
}


class Vertex {

String id;
Vertex next;
Edge first;

Vertex (String s, Vertex v, Edge e) {
id = s;
next = v;
first = e;
}

Vertex (String s) {
this (s, null, null);
}

@Override
public String toString() {
return id;
}

// TODO!!! Your Vertex methods here!

} // Vertex


class Edge {

String id;
Vertex target;
Edge next;

Edge (String s, Vertex v, Edge e) {
id = s;
target = v;
next = e;
}

Edge (String s) {
this (s, null, null);
}

@Override
public String toString() {
return id;
}

// TODO!!! Your Edge methods here!

} // Edge


class Graph {

String id;
Vertex first;

Graph (String s, Vertex v) {
id = s;
first = v;
}

Graph (String s) {
this (s, null);
}

@Override
public String toString() {
String nl = System.getProperty ("line.separator");
StringBuffer sb = new StringBuffer (nl);
sb.append (id + nl);
Vertex v = first;
while (v != null) {
sb.append (v.toString() + " --> ");
Edge e = v.first;
while (e != null) {
sb.append (e.toString());
sb.append ("(" + v.toString() + "->"
+ e.target.toString() + ") ");
e = e.next;
}
sb.append (nl);
v = v.next;
}
return sb.toString();
}

// TODO!!! Your Graph methods here!

} // Graph
}

最佳答案

显然,该图引用了第一个顶点,并且顶点本身链接在一起形成单链表。将顶点收集到 Java 列表中所需的全部代码应该是此代码:

public List<Vertex> allVertices(Graph g) {    
final List<Vertex> vertices = new ArrayList<>();
for (Vertex v = g.first; v != null; v = v.next)
vertices.add(v);
return vertices;
}

关于java - 计算图中所有顶点的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13627151/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com