Question

I have an Edge class which stores: source (vertex), target (vertex) and weight.

I have a Vertex class which stores: name, x-coordinates, y-coordinates, and Edge[] adjacentList.

I also have a Graph class which stores two ArrayLists: edges and vertices.

Currently when a vertex/node and edge is plotted it is automatically added to the vertices and edges list respectively.

Now I would like to fill the Edge[] adjacentList using these two array lists but I am not sure how to do this. I would appreciate it if someone is able to give me pointers or an outline of how the code would look like.

Thank you.

Was it helpful?

Solution

First of all there is redundancy in your code. The Edge class does not need to contain the source vertex because you are storing that edge into a Vertex class, so obviously that vertex will be the source.

Now to add an edge to adjacency list of any vertex:

Suppose you have two vertex: A and B. where A is the source and B is the target vertex. To create an edge just create an instance of Edge class(obviously there is a constructor defined) and add it to adjacency list of Vertex A.

Edge e1= new Edge('B' , weightofedge);

Suppose instance of Vertex is v1 i.e Vertex A then v1.adjacentList[index]=e1;

Or you can do it in one line too.

OTHER TIPS

I would create an .either method (which takes an Edge as a param and returns either Vertex) and an .other method (which takes a Vertex and returns the other Vertex of its Edge). Iterate through your edges list in the Graph class. For each edge, call .either to get one Vertex, store it in some variable, let's call it v1. Now call .other to get the other Vertex, call it v2.

Add the v1, v2 combination to both v1's Edge[] and v2's Edge[].

There are some ways of implementing a Graph:

You can have Vertex class in which every instance hold ArrayList that contains his neighbors, Or you can have a bool |V|X|V| Matrix that if Matrix[i][j] is true means you have directed edge from Vertex i to Vertex j.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top