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.
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 am having trouble comprehending how to scan in an adjacency list to a graph. I understand how adjacency tables work and their mapping to each other but what I don't understand is what type of data type to store them in. My assignment is to take an input file that tells the number of vertexes G=(V,E) and gives the edges to the other numbers in the graph.
So for example:
3
010
101
110
so:
0 maps to 1
1 maps to 0
2 maps to 0
2 maps to 1
From there I have to implement a breath search and a depth search on them. Would a hash table be my best bet?
The difference of using BFS and DFS is in which data structure you store the data, one is a "queue" the other is a "stack" (your answer). If you use a java list, you could get them from the beginning or from the end, but you can also use "real" stack and queue.
So in your case, create a List, and store the origin of your search in it.
After a while loop, while you have elements in your list keep it going.
So pick your element from the list ( first or last) and evaluate if it is your target, if it is not, store all its neighbors in the list and keep it going.
You may add something two stop adding the same element twice, you should have a list of visited nodes.
But, I have doubts if you wanted to know where to store the adjacency list. An array of lists would do. Every vertex, vertex[i] has a List with all the vertices that is connected to.
I have an input text file containing a line for each edge of a simple undirected graph. The file contains reciprocal edges, i.e. if there's a line u,v, then there's also the line v,u.
I need an algorithm which just counts the number of 4-cycles in this graph. I don't need it to be optimal because I only have to use it as a term of comparison. If you can suggest me a Java implementation, I would appreciate it for the rest of my life.
Thank you in advance.
Construct the adjacency matrix M, where M[i,j] is 1 if there's an edge between i and j. M² is then a matrix which counts the numbers of paths of length 2 between each pair of vertices.
The number of 4-cycles is sum_{i<j}(M²[i,j]*(M²[i,j]-1)/2)/2. This is because if there's n paths of length 2 between a pair of points, the graph has n choose 2 (that is n*(n-1)/2) 4-cycles. We sum only the top half of the matrix to avoid double counting and degenerate paths like a-b-a-b-a. We still count each 4-cycle twice (once per pair of opposite points on the cycle), so we divide the overall total by another factor of 2.
If you use a matrix library, this can be implemented in a very few lines code.
Detecting a cycle is one thing but counting all of the 4-cycles is another. I think what you want is a variant of breadth first search (BFS) rather than DFS as has been suggested. I'll not go deeply into the implementation details, but note the important points.
1) A path is a concatenation of edges sharing the same vertex.
2) A 4-cycle is a 4-edge path where the start and end vertices are the same.
So I'd approach it this way.
Read in graph G and maintain it using Java objects Vertex and Edge. Every Vertex object will have an ArrayList of all of the Edges that are connected to that Vertex.
The object Path will contain all of the vertexes in the path in order.
PathList will contain all of the paths.
Initialize PathList to all of the 1-edge paths which are exactly all of edges in G. BTW, this list will contain all of the 1-cycles (vertexes connected to themselves) as well as all other paths.
Create a function that will (pseudocode, infer the meaning from the function name)
PathList iterate(PathList currentPathList)
{
newPathList = new PathList();
for(path in currentPathList.getPaths())
{
for(edge in path.lastVertexPath().getEdges())
{
PathList.addPath(Path.newPathFromPathAndEdge(path,edge));
}
}
return newPathList;
}
Replace currentPathList with PathList.iterate(currentPathList) once and you will have all of the 2-cyles, call it twice and you will have all of the 3 cycles, call it 3 times and you will have all of the 4 cycles.
Search through all of the paths and find the 4-cycles by checking
Path.firstVertex().isEqualTo(path.lastVertex())
Depth-first search, DFS-this is what you need
Construct an adjacency matrix, as prescribed by Anonymous on Jan 18th, and then find all the cycles of size 4.
It is an enumeration problem. If we know that the graph is a complete graph, then we know off a generating function for the number of cycles of any length. But for most of other graphs, you have to find all the cycles to find the exact number of cycles.
Depth first search with backtracking should be the ideal strategy. Implement it with each node as the starting node, one by one. Keep track of visited nodes. If you run out of nodes without finding a cycle of size 4, just backtrack and try a different route.
Backtrack is not ideal for larger graphs. For example, even a complete graph of order 11 is a little to much for backtracking algorithms. For larger graphs you can look for a randomized algorithm.
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.
Say I have a list of edges each containing two nodes (to and from). What is the best way to find the edge two given nodes? Note that nodes in the edge may repeat.
Say I have edge in this format:
1 <-> 5
3 <-> 7
5 <-> 6
2<-> 6
Then query such as 1 5 will return true.
Then query such as 5 2 will return true because 5 connects 6 and 6 connects to 2.
Then query such as 1 7 will return false.
Then query such as 7 4 will return false since 4 doesnt exist, it means it is edge-less node.
It sounds to me like you are just asking if a path exists between two vertices in an undirected graph, but not necessarily what that path might be. This is the same as asking if the two vertices are in the same connected component of the graph.
If you really do only need to know if the two vertices are in the same connected component, then there is a simple and efficient algorithm using a Disjoint-set data structure.
initialize the disjoint set structure (DSS)
for each edge:
for each vertex in edge:
if the vertex does not exist in the DSS:
create a new subset in the DSS containing only the vertex
merge the subsets of the two vertices
To determine if a path exists between two vertices after processing all the edges, just check if the two vertices are in the same subset. If they are, then some path exists between them.
With an efficient implementation of the DSS, this algorithm achieves just slightly worse than linear time, and even with a simple linked-list implementation of the DSS it's O(n*log(n)). As j_random_hacker mentions, Floyd-Warshall is O(n^3) time and O(n^2) storage no matter if you are only calculating transitive closure or not, and using Dijkstra's algorithm requires an O(n*log(n)) calculation for each query.
You are basically looking forward to test if a given pair of nodes have a path in between them or not. This is a general case of the shortest path problem. Note, however, it suffices if we can find a shortest path between the pair of nodes in question. Use whatever representation suits you (adjacency matrix, adjacency list, edge-sets, union-find ...) and go ahead with a BFS/Djikstra implementation for all pair of nodes. It is then only a matter of servicing queries. Or, you can run Djikstra/BFS on a lazy basis (and cache past computations on an incremental manner).
Check out JGraphT library, it specializes in graph algorithms and does what you need.
You probably want some variation of Floyd algorithm for finding shortest paths between all graph verteces. As far as I can tell, you need only transitive closure of an undirected graph. Here is pseudocode:
for k = 1 to n
for i = 1 to n
for j = 1 to n
W[i][j] = W[i][j] or (W[i][k] and W[k][j])
W before running this code should be a binary adjacency matrix for a graph (W[i][j] == 1 <-> there is an edge from i to j).
After it will be a transitive closure. I.e. W[i][j] would be equal to 1 if and only if j is reachable from i.