Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

How to determine whether a graph contains a cycle, in Java?

/*
	This is an implementation that determines
	whether or not a directed graph contains a 
	cycle. A cycle is a number of vertices that
	are connected in a closed chain.
	
	Let V be the number of vertices and E the 
	number of edges.
	Time complexity: O(V + E) 
	Space complexity: O(V)
*/
import java.util.List;
import java.util.ArrayList;

public class CycleInGraph {
	private boolean cycle;
	// WHITE: Vertex not processed yet
	// GRAY: Vertex is being processed
	// BLACK: Vertex already processed
	private final int WHITE = 0, GRAY = 1, BLACK = 2;
	private int[] colors;
	private List<Integer[]> edges;

	public CycleInGraph() {
		cycle = false; // Cycle indicator

		// Create list of Graph edges
		edges = new ArrayList<>();
		edges.add(new Integer[] { 1, 3 }); // Edges sourced at vertex 0
		edges.add(new Integer[] { 2, 3, 4 }); // Edges sourced at 1
		edges.add(new Integer[] { 0 }); // Edges sourced at vertex 2
		edges.add(new Integer[] {}); // Edges sourced at vertex 3
		edges.add(new Integer[] { 2, 5 }); // Edges sourced at vertex 4
		edges.add(new Integer[] {}); // Edges sourced at vertex 5

		// Colors array to assign a color per vertex
		colors = new int[edges.size()];
	}

	public static void main(String[] args) {
		CycleInGraph application = new CycleInGraph();
      	// There are multiple cycles in considered graph:
		// 1) 0 -> 1 -> 2 -> 0
		// 2) 0 -> 1 -> 4 -> 2 -> 0
		// 3) 1 -> 2 -> 0 -> 1
		System.out.println(application.cycleInGraph()); // true
	}

	public boolean cycleInGraph() {
		for (int vertex = 0; vertex < edges.size(); vertex++) {
			// Traverse graph using DFS algorithm
			if (!cycle && colors[vertex] == WHITE) {
				dfs(vertex);
			}
		}

		return cycle;
	}

	private void dfs(int vertex) {
		colors[vertex] = GRAY;
		// Examine neighbors of current vertex
		Integer[] neighbors = edges.get(vertex);
		for (int neighbor : neighbors) {
			// There is cycle if neighbor already
			// processed in DFS traversal.
			if (colors[neighbor] == GRAY) {
				cycle = true;
				return;
			} else {
				dfs(neighbor);
			}
		}
		colors[vertex] = BLACK;
	}
}
Comment

PREVIOUS NEXT
Code Example
Java :: How to perform quick sort, in Java? 
Java :: java create file in folder 
Java :: get request in java 
Java :: java string to float 
Java :: get the image from camera click in android 
Java :: No Java executable found in current PATH: /bin:/usr/bin:/sbin:/usr/sbin 
Java :: string tokenizer java 
Java :: java quit application 
Java :: uuid from any string java 
Java :: javafx text wrapping 
Java :: clone array in java 
Java :: Get the last day of a month in Java 
Java :: Spring boot enable openapi swagger accessed 
Java :: Send image file to server useing Retrofit 
Java :: List into string java 
Java :: react The href attribute is required for an anchor to be keyboard 
Java :: No Java files found that extend CordovaActivity. [ERROR] An error occurred while running subprocess cordova. 
Java :: spring swagger 
Java :: get length of a string java 
Java :: java system.out.println 
Java :: java scan a file 
Java :: get device token firebase 
Java :: how to find length of array in java 
Java :: java 8 find in list 
Java :: java hello word 
Java :: String remove duplicate method in java 
Java :: Binary tree using linked list in Java 
Java :: android maven dependency 
Java :: declare array with size java 
Java :: java program to remove duplicate words in a string 
ADD CONTENT
Topic
Content
Source link
Name
1+3 =