create a directed graph
i want create a directed graph , i have three variables : String x,y,z and the first vertex contain the 3 variables and the next contain the next 3 until the end of the loop
i have this:
BufferedReader reader = new BufferedReader(
开发者_开发技巧 new StringReader(contentTextArea.getText()));
try {
str =reader.readLine();
while(str != null) {
String splitted[] = str.split("\\|");
String x = splitted[0].trim();
String y = splitted[1].trim();
String z = splitted[2].trim();
}
}
so this code give me each time 3 strings and i want for each time to create a vertex and an edge and this will create a graph at the end.
the code could be like this, but i don't know what to write inside
createVertex (String x,y,z)
,addEdge ()
methods.
public class graph {
createVertex (String x,y,z);
addEdge ();
}
If you want to create a linestrip, i.e. each line represents a vertex and an edge is formed by two consecutive vertices you could create/use a Vertex
class representing a vertex and an Edge
class that has a reference to the 2 vertices that form its end points.
In your graph class you could then just have a list of vertices and a list of edges.
createVertex()
could then just add a new vertex to the list whereas addEdge()
would create an edge using the last two vertices on the list (if there are at least two!) and put the edge on the edge list.
If you later have edges that are formed by specific vertices (i.e. not the two last ones) you might use the index of each vertex in the list to reference them and define the edge via those indices (i.e. edge from vertex 0 to 5 could be defined as 0,5
).
That really depends on how you are representing your graph. I would recommend using a third party library such as JGraph or JGraphT. If you can't use a third party library (e.g. for homework or you just want to learn) then you need to define your own Graph class.
Two common representations are connectivity matrices and adjacency lists. Either representations could work for you.
Creating a new vertex is easy, just call addVertex on the JGraph graph. That will return a vertex object. You will need to provide it with two parameters, a name and a data object. For the name either use an incrementing id number or the original line string. You'll then need to create a data object out of the three strings, providing a custom data object makes the most sense to me.
I would keep track of the last node inserted (starts null) and then create edges between vertices whenever the previous i s not null. Making sure to update the previous vertex every iteration.
精彩评论