简体   繁体   中英

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. I would then have to connect this coordinate to (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. 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. Option 2 gives you some more flexibility, such as adding weights to the edge values.

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这样已经制作好的

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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