Convert a matrix in graph - java

I have a problem in Java.I must create a graph. For input I have a char[][].
The graph has this proprerty:
Give an char's matrix and we suppose that this is in position [i][j].
Then I have a Node in the graph that represent this position.
The node that represent the position [i][j] has an edge with the node that represent(if possible):
the position'[i+1][j]'
the position '[i-1][j]'
the position'[i][j+1]'
The position'[i][j-1]'
But I have a problem in through the matrix and create an edge with this property. I think so I use a recursive algorithm. It's correct?
Thank to all

Related

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.

how to calculate outdegree of DAG which is represented using adjancency matrix

i need a method to calculate outdegree of each vertex of DAG to check whether it is leaf or not.i m using java with boolean adjancency matrix representation
Sum along the row.
In an adjacency matrix, there is a 1 at position (i, j) if there is an edge from vertex i to vertex j. Therefore, all the outgoing edges of vertex i are in row i. A sum of row i therefore gives you the outdegree of vertex i.
For a transposed adjacency matrix, sum along the columns.
Like David says, if you're only interested in whether the outdegree is zero or not you can save work by stopping the summation if you find a 1.

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...

Simplest algorithm to find 4-cycles in an undirected graph

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.

Java implementation of adjacency list

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.

Categories