Skip to content

Instantly share code, notes, and snippets.

@thmain
Created January 9, 2018 03:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thmain/b3d46614b0609535b52cfee48acbaf62 to your computer and use it in GitHub Desktop.
Save thmain/b3d46614b0609535b52cfee48acbaf62 to your computer and use it in GitHub Desktop.
import java.util.LinkedList;
public class GraphPrintAllPaths {
public void print(Graph graph, int start, int end, String path, boolean[] visited){
String newPath = path + "->" + start;
visited[start] = true;
LinkedList<Node> list = graph.adjacencyList[start];
for (int i = 0; i <list.size() ; i++) {
Node node = list.get(i);
if(node.destination!=end && visited[node.destination]==false){
// visited[node.destination] = true;
print(graph,node.destination,end,newPath,visited);
}else if(node.destination==end){
System.out.println(newPath + "->" + node.destination);
}
}
//remove from path
visited[start] = false;
}
public void printAllPaths(Graph graph, int start, int end){
boolean[] visited = new boolean[graph.vertices];
visited[start] = true;
print(graph, start, end, "", visited);
}
public static void main(String[] args) {
int vertices = 6;
Graph graph = new Graph(vertices);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 2);
graph.addEdge(1, 3);
graph.addEdge(3, 4);
graph.addEdge(2, 3);
graph.addEdge(4, 0);
graph.addEdge(4, 1);
graph.addEdge(4, 5);
GraphPrintAllPaths p = new GraphPrintAllPaths();
p.printAllPaths(graph,0,5);
}
}
class Graph{
int vertices;
LinkedList<Node> [] adjacencyList;
public Graph(int vertices){
this.vertices = vertices;
adjacencyList = new LinkedList[vertices];
for (int i = 0; i <vertices; i++) {
adjacencyList[i] = new LinkedList<Node>();
}
}
public void addEdge(int source, int destination){
Node node = new Node(source, destination);
//add edge
adjacencyList[source].addLast(node);
}
}
class Node{
int source;
int destination;
public Node(int source, int destination) {
this.source = source;
this.destination = destination;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment