Data Structure Undirected Graph in Java - java

Assume an undirected graph where edges have int values.
Example Graph:
A---B---C
|
D
Example Edge Values:
A,B : 1
B,C : 2
B,D : 2
I am writing a program that does the following: Given a node, return all edges in which the node is involved together with the associated value. For example: IN: B → OUT: (C,2), (D,2). Or IN: C → OUT: (B,2).
I am looking for an efficient data structure to do that. The problem is not derived from graph theory, I just used that to explain it. I am not interested in shortest paths etc., just this kind of data store.
The only thing I could quickly come up with:
HashMap<String,Tuple>
where
class Tuple{
String node;
int value;
}
I would then put each edge in this set twice, for example (pseudocode):
hm.add(A, new Tuple(B,1))
hm.add(B, new Tuple(A,1))
Is there a more efficient way to do this?

How about Guava’s ValueGraph?
https://github.com/google/guava/wiki/GraphsExplained

Related

Graphs: DFS visit and Java implementation

I'm trying to implement a recursive Depth-First Search for a graph in Java language.
Assumptions
The graph is represented with adjacency lists.
GraphSearchImpl is a data structure that stores the result of a visit.
GraphSearchImpl contains arrays that store, for each vertex, start/end times, visit status (UNDISCOVERED, DISCOVERED, CLOSED), weight of the path etc etc..
All vertices have a unique index mapped in a HashMap, where the String is a unique label for each vertex. I'm reading/writing arrays cells, for a specified vertex, using this index.
Code
public void visitDFSRecursive(GraphSearchImpl search,VertexImpl u,Integer time) {
int index = search.getIndexOf(u);
search.status[index]=VertexImpl.DISCOVERED;
time++;
search.startTimes[index]=time;
for (VertexImpl v: u.getAdjList()) {
int adjIndex = search.getIndexOf(v);
if (search.status[adjIndex]==VertexImpl.UNDISCOVERED) {
search.status[adjIndex]=VertexImpl.DISCOVERED;
search.parents[adjIndex]=u;
visitDFSRecursive(search,v,time);
}
}
search.status[index]=VertexImpl.CLOSED;
time++;
search.endTimes[index]=time;
}
I'm calling this method like this, over a graph with just two nodes (A -> B):
g.visitDFSRecursive(search,sourceVertex,new Integer(0));
The output is the following:
-A starts at 1 ends at 2
-B starts at 2 ends at 3
It's obviously wrong, because the time interval of start/end of B must be included in the A's one, since B is a son of A in this graph.
I know the problem is that I'm not using time counter right.
Please suggest.
The problem is that time is a local variable, so when you increment it up in your recursion, the time for A is not affected. You should convert it to a global/static variable, or make an integer wrapper class and pass it through a mutable object.

Representing a map and running A* on it

My question is mainly about map representation and I would like your opinions.
Having a map represented by a bunch of roads and a connection between them - let's say road A is connected to B,C,D on one edge but there are only turns possible from A to C and D.
Let's say I represent this by a graph where each road is an edge and each road meeting/end is a vertex.
I want to run an A* or any other on such representation but... moving from node to node in the graph I strictly need to know where did I come from... I mean - from what direction. The next vertexes I can move to depend on the open turns that I have.
I can keep where I came from but I also want this to be as generic as possible and the simple graph solution doesn't provide me a knowledge where do I come from.
Could you please advice me how would you approach this one?
Thanks!
Represent each node as a bunch of nodes, one for each incoming road.
So let us have the following graph.
And let use the following rules:
If Came to B from A than we can only turn to D
If Came to B from C than we can only go to E
If Came to C from A than we can go to both B and D
If Came to C from E than we can only go to B
Than we have the following equivalent graph, now every node marked by original name and incoming road:
This is universal way that allow as to use any standard algorithm for directed graph in such situation. For some algorithms you may need to create fake source or initial and sink or goal nodes to handle that in such graph they can be represented as several nodes each, in current case we may need an additional node to describe behavior if we start from this nose, instead of coming from some other, but generally it is just original structure represented as classical graph.
Also we don't really need to split A, D or E if they always have the same behavior.

How to implement Greedy Search algorithm

I have a project that is given on my Artificial Intelligence course. I need to implement Greedy Search algorithm for my program. Description of my project is:
Two text files called “tree.txt” and “heuristic.txt” are given. “tree.txt” will define the search tree where each line will contain a parent-child relation and a path cost between them. Each data will be seperated with a space.
e.g.
A B 5
A C 3
B D 6
The first character in the first line will be the Start node (A in here) and the goal node will be “G”.
“heuristic.txt” will define the heuristic, h(n), values. Each line will contain the heuristic value of each node. Each data will be seperated with a space.
e.g.
A 20
B 15
C 18
Output:
The program should give the solution path and the path cost from start node to goal.
Now my problem is that i am familiar with Greedy Search theoretically, but never implemented it practically in coding. I really dont know from where to start. We are free to develop our program in any language. Mostly, i have skills in Java and C#. If anybody can give me some ideas, or help me with any similar examples or tutorials. Any kind of help will be greatly appreciated. Sorry for so much writing. Thank you in advance:)))
I suggest this solution using python.
To implement the graph in your program use a simple python dictionary. Here's the code:
class Tree:
def _init_(self,dict,heuristic):
self.tree=tree
self.heuristic=heuristic
def getHeuristicValue(self,state)
value=self.heuristic.get(state)
return value
The constructor call is something like:
g = Graph({'A':{'B':5,'C':3},'B':{'D':6}},{'A':20,'B':15,'C':18})
The getHeuristic python function pass accepts a state as an argument and returns the value of the heuristic of this state.
To learn about python's dictionary class I suggest you read the tutorial
To implement the search algorithm with python you should implement this simple pseudocode:
function Tree-Search(initialNode,goalNode) returns a solution,or failure
frontier.push(initialNode) with the value of the function heuristic(initialNode.state)+the path cost to reaxh this node
while(frontier)
node<-frontier.pop()
if node.state==GoalNode.state
return node
expand node, adding the resulting nodes to the frontier
return None
For the frontier you must use a priority queue because you must pop the node with the lower value of g(n)+h(n) (where g(n) is the path cost to reach this node and h(n) is the value of the heuristic function).
To implement priority queue you should use a heap of the standard library heapq
The node is a data structure that must contain four components:
node.state:the state in the state space to which the node corresponds.
node.parent:the node in the search tree that generated this node.
node.action: the action that was applied to the parent to generated the node.
node.pathCost: is g(n),the cost of the path from the initial state to the node.
Lastly, for expanding the node, you can use this python function:
def actions(self,state):
'''return a tuple that contain the state child of state '''
return tuple(self.tree.get(state))
I suggest you to look this for your problem.
You can get the solution simply go back from the node.state that returns from the output of the algorithm while node.parent is not null that is your solution.
I hope this is useful for your project.

Shortest Path Algorithm : Uniform distances from one point to adjacent points

I am trying to develop an algorithm wherein I have a Location Class. In each class, I create a list of its adjacent Locations. I want to know, how can I get the shortest path from one Location to another. I am trying to look for different algorithms but it seems that they doesn't answer my problem.
For example, I have a point A and I want to go to point B,
A - - C - - H - - J
|
F- - K- -B
My idea for this is if B is in the List of adjacent locations of A, then that is the shortest path. If not, it should search the adjacent locations of the adjacent locations of A. But I do not know how to implement this in code or if it is a good algorithm. I also want to display A - C - F - K - B as the route for the shortest path. I am also developing this one on j2me so I am a bit limited on the java features that I can use.
If anyone can help me, it will be much appreciated. Thanks
You are on the right track. What you describe is the start of BFS. BFS is a shortest-path algorithm that is both optimal [finds the shortest path] and complete [always finds a path if one exist] for unweighted graph - so it is probably the right choice.
BFS works on graphs. In here your graph is G = (V,E) such that V = {all locations} [the nodes/vertices/locations] and E = {(u,v),(v,u) | u and v are neighbors} [the edges/links/neighbors]
The idea of BFS is simpilar to what you are suggesting: first check if the starting node is also the target. Then check if one of the neighbors of the starting node is the target, then search for their neighbors....
Regarding getting the actual path from BFS: have a look at this post.
The idea is to maintain a map - for each node [location] - the map will indicate how did you get there? which node discovered it? After the BFS finished - follow the map from target to source, and you get the actual path [reversed of course]. The link provided gives more details about this idea.
Your problem is known in the computing world as a graph search problem, looking for the shortest path between two nodes. Graphs here are not the x and y axis graphs from math, but Nodes (or Locations in your example) connected by edges.
Dijkstra's algorithm is the most commonly used to find the shortest path between two nodes, and for your use case it is simplified slightly because the edges in your scenario all have a weight (or cost) of one. An implementation of this is available in JGraphT, though I'm not sure how easy that is to include in a J2ME environment.
Have a look at the A* algorithm Dijkstra's pathfinding algorithm.

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.

Categories