What are the different types of Graph ADT's that can you implement in java, can you provide a link or list? For example, a queue in java can be further specified into a Linked List.
Adjacency List Structure
"Vertices are stored as records or objects, and every vertex stores a list of adjacent vertices. This data structure allows the storage of additional data on the vertices. Additional data can be stored if edges are also stored as objects, in which case each vertex stores its incident edges and each edge stores its incident vertices."
Adjacency Matrix
"A two-dimensional matrix, in which the rows represent source vertices and columns represent destination vertices. Data on edges and vertices must be stored externally. Only the cost for one edge can be stored between each pair of vertices."
Incidence Matrix
"A two-dimensional Boolean matrix, in which the rows represent the vertices and columns represent the edges. The entries indicate whether the vertex at a row is incident to the edge at a column."
Source: https://en.wikipedia.org/wiki/Graph_(abstract_data_type)
Related
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.
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...
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.
Hi I'm going about implementing a Graph data structure for a course (the graph isn't part of the requirement, I've chosen to use it to approach the problem) and my first thought was to implement it using an adjacency list, because that requires less memory, and I don't expect to have that many edges in my graph.
But then it occurred to me. I can implement an adjacency list Graph data structure using a Map (HashMap to be specific). Instead of the list of vertices I'll have a Map of vertices, which then hold a short list of edges to vertices.
This seems to be the way to go for me. But I was wondering if anyone can see any drawbacks that a student such as I might have missed in using a HashMap for this? (unfortunately I recall being very tired whilst we were going over HashMaps...so my knowledge of them is less than all the other data structures I know of.) So I want to be sure.
By the way I'm using Java.
The two primary ways of representing a graph are:
with the adjacency list (as you mentioned)
with the adjacency matrix
Since you will not have too many edges (i.e. the adjacency matrix representing your graph would be sparse), I think your decision to use the list instead of the matrix is a good one since, as you said, it will indeed take up less space since no space is wasted to represent the absent edges. Furthermore, the Map approach seems to be logical, as you can map each Node of your graph to the list of Nodes to which it is connected. Another alternative would be to have each Node object contain, as a data field, the list of nodes to which it is connected. I think either of these approaches could work well. I've summed it up below.
First approach (maintain the map):
Map<Node, Node[]> graph = new HashMap<Node, Node[]>();
Second approach (data built into Node class):
public class Node {
private Node[] adjacentNodes;
public Node(Node[] nodes) { adjacentNodes = nodes; }
public Node[] adjacentNodes() { return adjacentNodes; }
}
Graphs are traditionally represented either via an adjacency list or an adjacency matrix (there are other ways that are optimized for certain graph formats, such as if the node id's are labeled sequentially and/or you know the number of nodes/edges ahead of time, but I won't get into that).
Picking between an adjacency list and an adjacency matrix depends on your needs. Clearly, an adjacency matrix will take up more space than an adjacency list (matrix will always take (# of nodes)^2 whereas a list will take (# of nodes + # of edges), but if your graph is "small" then it doesn't really make a difference.
Another concern is how many edges you have (is your graph sparse or dense)? You can find the density of your graph by taking the # of edges you have and dividing it by:
n(n-1) / 2
Where "n" is the number of nodes of the graph. The above equation finds the total # of possible edges in an "n" node UNDIRECTED graph. If the graph is directed, remove the " / 2".
Something else to think of is if efficient edge membership is important. An adjacency list can detect edge membership easily (O(1)) since it's just an array lookup - for an adjacency list if the "list" is stored as something other than a HashSet it will be much slower since you will have to look through the entire edgelist. Or maybe you keep the edgelist's sorted and you can just do a binary search, but then edge insertion takes longer. Maybe your graph is very sparse, and adjacency matrix is using too much memory, so you have to use an adjacency list. Lot's of things to think about.
There's a lot more concerns that may relate to your project, I just list a few.
In general, assuming your graph isn't very complex or "big" (in the sense of millions of nodes), a HashMap where the key is the node ID and the value is a Set or some other collection of node ID's indicating neighbors of the key node is fine, I've done this for 400,000+ node graphs on an 8gb machine. A HashMap based implementation will probably be easiest to implement.
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.