Java implementation of adjacency list - java

I have a n*m matrix with integer value at each node and its an undirected graph. I want to build an adjacency list for it. How do I do that? Any help is much appreciated.

Here is a simple implementation for creating adjacency list.According to the problem:
There will be n linked lists each of variable size.
First Initialize an ArrayList of linked lists of integers:
ArrayList<LinkedList<Integer>> adj_list = new ArrayList<LinkedList<Integer>>();
Then simply add linked lists by repeating following code:
adj_list.add(new LinkedList<Integer>());
If you are using it to represent graph,then no of linked lists=no of vertices.So you must repeat the above line n(no of vertices) times.
Say now you want to add numbers 3,4,5 to your first linked lists.Do the following:
adj_list.get(0).add(3);
adj_list.get(0).add(4);
adj_list.get(0).add(5);
It simply means there is an edge in your graph from vertex 0 to 3,4,5.

First your description seems to be of an adjacency matrix except you're saying m by n. Adjacency matrices are always square, so we must assume m==n. The matrix elements are the edge weights.
An adjacency list representation of a graph is (usually) an array adj of sets of pairs. The set adj[i] contains pair <j, w> iff there is a directed edge i--w-->j, i.e. from vertex i to j with weight w in the represented graph.
With this definition, it's clear you must start with n empty adjacency sets adj[i] and then iterate over the matrix elements m[i][j] = w. For each of these add <j, w> to adj[i].
The java code for this is pretty trivial, so I won't write it. The type for a graph represented with adjacency lists is something like ArrayList<HashMap<Integer, Integer>> adjacencies. The pairs <j,w> in adj[i] are mappings j -> w stored in the hash table adjacencies.get(i). The code to create such an adjacency will be adjacencies.get(i).put(j, w).
This method allows you to iterate over the vertices adjacent to i by iterating over keys in the hash table adjacencies.get(i), look up the weight of a given edge i--w-->j with w = adjacencies.get(i).get(j), and so on for all the usual graph operations.

Related

How to identify whether to use anjency matrix or abjency array according to situation

I want to find the best method to make a graph according to the situation.If its abjacency Matrix or array
Graph on array(adjacency matrix) O(n^2) memory versus O(n*m) adjacency list(m <= n). Iterate on vertex's edges O(n), what also greater than adjacency list. Many libraries, containing graph algoritihms founded on adjacency list. But if you have tightly graph, where n ~= m, array its ok.

Check for Cycles in Adjacency Matrix?

One of my methods in Java passes in an adjacency matrix with
1 values in matrix indicating a connection, and
0 values indicating no connection.
My adjacency matrix represents an un-directed graph.
How can I check whether my adjacency matrix has any cycles or not?
There is two good solutions:
begin to traverse (bfs, dfs , ...) your graph if you visited a node twice there is cycle in your graph.
hence you have a adjacency matrix, then you could use algorithm that Imran mentioned in comment, you just need to compute An, for n = 1 , .... and check if there is non zero diagonal entry or not, and I think your teacher wants this algorithm.
Just google adjacency matrix properties and you will find articles like this.

Find and discard shared edges between polygons

I have an array of convex polygons which may share edges (each polygon is represented by an array of its vertices). When some of these polygons share edges, I'd like to create a new polygon from the unique edges, disregarding the shared ones. The output should be an array of (merged) polygons with unique edges. The closest algorithms I can find calculate a convex hull, which is close to what I'm trying to achieve but not quite.
Computing the convex hull of polygons with shared edges does not work, because by definition the result is a convex polygon. While in your case, the result of merging multiple convex polygons with shared edges may not be convex anymore.
I would propose the following approach (it's not trivial, I don't know whether it can be done in a simpler way):
Change the representation of the polygons to arrays of vertex indices (this simplifies some of the later steps)
Traverse all polygons and append all their vertices to a large array of vertices. While iterating over the vertices of a polygon and appending them to the large array, generate a small array of corresponding vertex indices (the new polygon representation). A polygon is now an array of vertex indices referring to the large array of vertices (used by all the polygons).
Identify shared vertices
Maintain a map from vertex index to counter (a vertex index is the index of a vertex in the large array of vertices created in 1.). This will keep track of how many polygons a vertex belongs to and allow to identify shared vertices.
Traverse all polygons and their vertex indices and for each vertex index you have, insert it in this map or increment the counter if it is already in the map.
Identify shared edges (and keep track of which polygons they belong to)
Maintain a map from (i, j) (with i < j) from pairs of vertex indices to (counter, polygon index1, polygon index2).
The constraint i < j make sure edges with different orientation are not counted twice (this also means when querying the map you have to make sure that i < j in your query pair).
The counter counts the number of polygons an edge belongs to. The problem is in 2D and I assume the data is clean (polygons are not overlapping each other), so the value of this counter should be either 1 or 2.
The polygon index1 and polygon index2 are referring to the indices of polygons the edge may belong to in the array of polygons (these indices can be initialized to -1).
Traverse all the polygons and their edges (iterate over the list of vertex indices without forgetting the final edge closing the loop). For each edge (i, j) with i < j, update the map by either creating the entry in the map, or updating its counter and polygon indices.
Generate the new array of polygons
Iterate over all the polygons from the initial array. For each polygon, a new polygon may be generated:
Find a vertex index in the polygon that is not shared (using the map from 2.). If there is no such vertex index, discard the polygon and move to the next non-discarded polygon.
Output the (non-shared) vertex index. Starting from this vertex index, iterate over all the edges of the polygon:
If the edge is not shared, output the destination vertex index and move to the next edge.
If the edge is shared, you need to find out which polygon it is shared with (to continue iterating over the edges of the new polygon). Use the edge map from 3. to do this. Locate the edge in the other polygon and continue iterating over the edges of this other polygon (in the opposite direction w.r.t. to the shared edge).
This iteration over the edges of the new polygon should eventually loop back to the starting (non-shared) vertex index, which means the new polygon is closed and can be appended to the new array of polygons.
While iterating over the edges of different polygons to generate the final merged polygon, the traversed polygons should be tracked, so that they can be discarded in the outer loop.
Convert the representation of the new polygons back to array of vertices (if needed)
Simply iterate over the new polygons and their array of vertex indices. Fetch the corresponding vertices from the array of vertices created in 1. and append it a new array of vertices for this polygon.
I dunno - make a list of all vertices and sort it by x and y values, then go through and discard the duplicates?
maybe GPC - General Polygon Clipper library can help. It has tons of features and algorithms. There is a Java port by Daniel Bridenbecker. I've used it to calculate polygon intersections and unions...

algorithm for implementing DFA as a linked list

I want to know how to implement a DFA as a linked list in C/C++/Java.
since every state can have several branches, you probably need more than one linked list. that means, every state has an array of n linked lists. so it's more like a tree structure with cycles than a simple linked list.
This is definitely possible, but would be grossly inefficient. What you would do is to simply store all your states in a link list, and then each state would need to keep a transition table. The transition table would look something like:
'a' -> 2
'b' -> 5
where your alphabet is {a,b}, and 2 and 5 are the states stored at position 2 and 5 in the linked list. As I said, this is definitely NOT how you would want to implement a DFA, but it is possible.
The first thing that came up in my mind is that,
create a class/struct called state with two array components. one for the states that can reach our state and one for the ones that are reachable from our state.
Then create a linked list whose elements are your states.
here's my implementation of this class
class state
{
private:
string stateName;
vector<state> states_before_me;
vector<state> states_after_me;
state* next;
//methods of this state
}
Single linked list couldn't represent the DFA efficiently. You can think DFA as a directed weighted graph data structure as states are vertices, transitions are edges, transition symbols are weights. There are two main method to implement graph structure.
i) Adjacency list: It basically has V(Number of vertices) linked lists. Each link list contains vertices which has edge to corresponding vertex. If we have vertices (1,2,3) and edges (1,2),(1,3),(2,1),(2,3),(3,3) corresponding adjanceny list is:
1->2->3
2->1->3
3->3
ii) Adjacency matrix: It is a VxV matrix with every entry at (i,j) symbolize an edge from i to j. The same example above represented like(1 means there is edge, 0 mean there is not):
1 2 3
1 0 1 1
2 1 0 1
3 0 0 1
But you must make little changes to these because your graph is weighted.
For list implementation you can change vertices in linklist to a struct which contains vertex and the weight of the edge connecting these vertices.
For matrix implementation you can place the weights directly into matrix instead of 0,1 values.
If you don't want to deal with the implementation of graph class there is libraries like Boost Graph Library which contains the two implementation and all the important graph algorithms DFS to Dijkstra's shortest path algorithm. You can look it up from http://www.boost.org/doc/libs/1_47_0/libs/graph/doc/index.html.

Represent Graph as a 2d Matrix

Lets say I have a graph of x nodes. I want to first represent it and then with help of a Algorithm Y, I would assign value to each of the node. Then I want to refresh the graph to display the value calculated.
Steps
1) Represent the graph as 2d Matrix. Perform processing over the 2d Matrix and then use the result to generate a new graph. [Better than doing processing by iterating the graph]
Problems:
1) I need to create a 2d Array with indexes as node names i.e string. I am not sure what's the best way to do this?
2) What's the best graph api which can A) produce good looking results 2) user friendly 3) allows vertex names as strings
I hope I made myself clear. Any input would be of immense help.
Thanks
Sunil
A Java array can't use strings as indexes, only non-negative integers. I think what you want is a java.util.Map. To get a two-dimensional structure, you probably want to create an array of Maps, or a Map that contains arrays, or something like that.
1) I need to create a 2d Array with indexes as node names i.e string. I am not sure what's the best way to do this?
Instead of using node names as indexes, you can arbitrarily label each node with an integer and use this as the index into the array. This is generally how adjancy matrices are implemented.
For example, if you have a graph of nodes A, B, C, D, E, and F, choose an arbitrary labeling like
0 -> A
1 -> B
2 -> C
3 -> D
4 -> E
5 -> F
You can store this in a Map<Integer, String> (or the reverse) if need be.
Then whenever there is an edge between two vertices, add a 1 (or the weight of the edge, if it is a weighted graph) to the matrix at that location.

Categories