简体   繁体   English

Java Graph实施帮助

[英]Help with Java Graph Implementation

I have to write up a program that stores verticies into a graph and connect them. 我必须编写一个程序将顶点存储到图中并连接它们。 The input for the program is given as: 该程序的输入为:

Plot 3 5 to 5 8
Plot 6 1 to 3 5
etc

From this input, I would store a vertix of (3,5) which are the x and y coordinates. 通过此输入,我将存储(3,5)的顶点,分别是xy坐标。 I would then have to connect this coordinate to (5,8) . 然后,我将不得不将此坐标连接到(5,8)

My question is, how would I go in implementing this graph? 我的问题是,我将如何实施该图? I was thinking I would need to store the vertixes in an arraylist or a map, and keep the edges in a list too...but since I'm not given an actual max size of the graph, I'm a little bit lost in the overall implementation. 我以为我需要将顶点存储在arraylist或map中,并将边缘也保留在列表中...但是由于我没有得到图形的实际最大尺寸,所以我有点迷失了在整体实施中。 Basically, if you guys could give me an idea how to start this, it'd be sweet as. 基本上,如果你们能给我一个如何启动它的想法,那会很不错。

An easy way to think about graphs is to break them down into their Node and Edge components. 考虑图形的一种简单方法是将它们分解为节点和边缘组件。 (Note: what you call a vertex I call a node. Close enough.) (注意:您所说的顶点我称为节点。足够接近。)

Let us consider the following options: 让我们考虑以下选项:

// Option 1
class Node<V> {
    V data;
    Set<Node<V>> edges;
    // if it were a directed graph, you'd need:
    // Set<Node<V>> edgesAway;
}

// Option 2
class Node<V> {
    V data;
    Set<Edge<V>> edges;
    // if it were a directed graph, you'd need:
    // Set<Edge<V>> edgesAway;
}

class Edge<V> {
    Node<V> source;
    Node<V> destination;
}

Now a graph is nothing more than: 现在,图表无非是:

// option 1
class Graph<V> {
    Set<Node<V>> nodes;
}

// option 2
class Graph<V> {
    Set<Node<V>> nodes;
    Set<Edge<V>> edges;
}

Option 1 is the simplest and easiest to implement. 选项1是最简单,最容易实现的。 Option 2 gives you some more flexibility, such as adding weights to the edge values. 选项2为您提供了更多的灵活性,例如为边缘值添加权重。

Now, you have some data at these nodes, correct? 现在,您在这些节点上有一些数据,对吗? For now, let's just have the data be the string representation of the coordinates. 现在,让我们将数据作为坐标的字符串表示形式。

class SomeObject {
    String data;
    int x;
    int y;

    public boolean equals(Object o) {
        if(o instanceof SomeObject) {
            SomeObject so = (SomeObject)o;
            return so.x == x && so.y == y;
        }
        return false;
    }

    public int hashCode() {
        return x * 100 + y; // it works... close enough :)
    }
}

// somewhere later:
Graph<SomeObject> graph = ...

Now as for what functionality you'll want you'd need a more complete list. 现在,您需要什么功能,您需要一个更完整的列表。 But this should get you well on your way to understanding how to implement a graph. 但这应该可以帮助您更好地理解如何实现图形。

您可以使用像JDSL这样已经制作好的

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

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