diff --git a/GraphProblem/GraphBFS.java b/GraphProblem/GraphBFS.java new file mode 100644 index 0000000..ed0d089 --- /dev/null +++ b/GraphProblem/GraphBFS.java @@ -0,0 +1,84 @@ +package GraphProblem; + +//Java program to print BFS traversal from a given source vertex. +//BFS(int s) traverses vertices reachable from s. +import java.io.*; +import java.util.*; + +//This class represents a directed graph using adjacency list +//representation +public class GraphBFS +{ + private int V; // No. of vertices + private LinkedList adj[]; //Adjacency Lists + + // Constructor + GraphBFS(int v) + { + V = v; + adj = new LinkedList[v]; + for (int i=0; i queue = new LinkedList(); + + // Mark the current node as visited and enqueue it + visited[s]=true; + queue.add(s); + + while (queue.size() != 0) + { + // Dequeue a vertex from queue and print it + s = queue.poll(); + System.out.print(s+" "); + + // Get all adjacent vertices of the dequeued vertex s + // If a adjacent has not been visited, then mark it + // visited and enqueue it + Iterator i = adj[s].listIterator(); + while (i.hasNext()) + { + int n = i.next(); + if (!visited[n]) + { + visited[n] = true; + queue.add(n); + } + } + } + } + + // Driver method to + public static void main(String args[]) + { + GraphBFS g = new GraphBFS(4); + + g.addEdge(0, 1); + g.addEdge(0, 2); + g.addEdge(1, 2); + g.addEdge(2, 0); + g.addEdge(2, 3); + g.addEdge(3, 3); + + System.out.println("Following is Breadth First Traversal "+ + "(starting from vertex 2)"); + + g.BFS(2); + } +} +//This code is contributed by Anilabha Baral diff --git a/GraphProblem/GraphBellman.java b/GraphProblem/GraphBellman.java new file mode 100644 index 0000000..f8fa9e1 --- /dev/null +++ b/GraphProblem/GraphBellman.java @@ -0,0 +1,136 @@ +package GraphProblem; + + +//A Java program for Bellman-Ford's single source shortest path +//algorithm. +import java.util.*; +import java.lang.*; +import java.io.*; + +//A class to represent a connected, directed and weighted graph +class GraphBellman { + // A class to represent a weighted edge in graph + class Edge { + int src, dest, weight; + Edge() + { + src = dest = weight = 0; + } + }; + + int V, E; + Edge edge[]; + + // Creates a graph with V vertices and E edges + GraphBellman(int v, int e) + { + V = v; + E = e; + edge = new Edge[e]; + for (int i = 0; i < e; ++i) + edge[i] = new Edge(); + } + + // The main function that finds shortest distances from src + // to all other vertices using Bellman-Ford algorithm. The + // function also detects negative weight cycle + void BellmanFord(GraphBellman graph, int src) + { + int V = graph.V, E = graph.E; + int dist[] = new int[V]; + + // Step 1: Initialize distances from src to all other + // vertices as INFINITE + for (int i = 0; i < V; ++i) + dist[i] = Integer.MAX_VALUE; + dist[src] = 0; + + // Step 2: Relax all edges |V| - 1 times. A simple + // shortest path from src to any other vertex can + // have at-most |V| - 1 edges + for (int i = 1; i < V; ++i) { + for (int j = 0; j < E; ++j) { + int u = graph.edge[j].src; + int v = graph.edge[j].dest; + int weight = graph.edge[j].weight; + if (dist[u] != Integer.MAX_VALUE && dist[u] + weight < dist[v]) + dist[v] = dist[u] + weight; + } + } + + // Step 3: check for negative-weight cycles. The above + // step guarantees shortest distances if graph doesn't + // contain negative weight cycle. If we get a shorter + // path, then there is a cycle. + for (int j = 0; j < E; ++j) { + int u = graph.edge[j].src; + int v = graph.edge[j].dest; + int weight = graph.edge[j].weight; + if (dist[u] != Integer.MAX_VALUE && dist[u] + weight < dist[v]) { + System.out.println("Graph contains negative weight cycle"); + return; + } + } + printArr(dist, V); + } + + // A utility function used to print the solution + void printArr(int dist[], int V) + { + System.out.println("Vertex Distance from Source"); + for (int i = 0; i < V; ++i) + System.out.println(i + "\t\t" + dist[i]); + } + + // Driver method to test above function + public static void main(String[] args) + { + int V = 5; // Number of vertices in graph + int E = 8; // Number of edges in graph + + GraphBellman graph = new GraphBellman(V, E); + + // add edge 0-1 (or A-B in above figure) + graph.edge[0].src = 0; + graph.edge[0].dest = 1; + graph.edge[0].weight = -1; + + // add edge 0-2 (or A-C in above figure) + graph.edge[1].src = 0; + graph.edge[1].dest = 2; + graph.edge[1].weight = 4; + + // add edge 1-2 (or B-C in above figure) + graph.edge[2].src = 1; + graph.edge[2].dest = 2; + graph.edge[2].weight = 3; + + // add edge 1-3 (or B-D in above figure) + graph.edge[3].src = 1; + graph.edge[3].dest = 3; + graph.edge[3].weight = 2; + + // add edge 1-4 (or A-E in above figure) + graph.edge[4].src = 1; + graph.edge[4].dest = 4; + graph.edge[4].weight = 2; + + // add edge 3-2 (or D-C in above figure) + graph.edge[5].src = 3; + graph.edge[5].dest = 2; + graph.edge[5].weight = 5; + + // add edge 3-1 (or D-B in above figure) + graph.edge[6].src = 3; + graph.edge[6].dest = 1; + graph.edge[6].weight = 1; + + // add edge 4-3 (or E-D in above figure) + graph.edge[7].src = 4; + graph.edge[7].dest = 3; + graph.edge[7].weight = -3; + + graph.BellmanFord(graph, 0); + } +} +//This code is contributed by Anilabha Baral. diff --git a/GraphProblem/GraphDFS.java b/GraphProblem/GraphDFS.java new file mode 100644 index 0000000..d98d9ee --- /dev/null +++ b/GraphProblem/GraphDFS.java @@ -0,0 +1,80 @@ +package GraphProblem; + + + +//Java program to print DFS traversal from a given given graph +import java.io.*; +import java.util.*; + +//This class represents a directed graph using adjacency list +//representation +public class GraphDFS +{ + private int V; // No. of vertices + + // Array of lists for Adjacency List Representation + private LinkedList adj[]; + + // Constructor + GraphDFS(int v) + { + V = v; + adj = new LinkedList[v]; + for (int i=0; i i = adj[v].listIterator(); + while (i.hasNext()) + { + int n = i.next(); + if (!visited[n]) + DFSUtil(n, visited); + } + } + + // The function to do DFS traversal. It uses recursive DFSUtil() + void DFS(int v) + { + // Mark all the vertices as not visited(set as + // false by default in java) + boolean visited[] = new boolean[V]; + + // Call the recursive helper function to print DFS traversal + DFSUtil(v, visited); + } + + public static void main(String args[]) + { + GraphDFS g = new GraphDFS(4); + + g.addEdge(0, 1); + g.addEdge(0, 2); + g.addEdge(1, 2); + g.addEdge(2, 0); + g.addEdge(2, 3); + g.addEdge(3, 3); + + System.out.println("Following is Depth First Traversal "+ + "(starting from vertex 2)"); + + g.DFS(2); + } +} +//This code is contributed by Anilabha Baral + + diff --git a/GraphProblem/PrimsAlgo.java b/GraphProblem/PrimsAlgo.java new file mode 100644 index 0000000..3a87754 --- /dev/null +++ b/GraphProblem/PrimsAlgo.java @@ -0,0 +1,111 @@ +package GraphProblem; + +//A Java program for Prim's Minimum Spanning Tree (MST) algorithm. +//The program is for adjacency matrix representation of the graph + +import java.util.*; +import java.lang.*; +import java.io.*; + +public class PrimsAlgo { + // Number of vertices in the graph + private static final int V = 5; + + // A utility function to find the vertex with minimum key + // value, from the set of vertices not yet included in MST + int minKey(int key[], Boolean mstSet[]) + { + // Initialize min value + int min = Integer.MAX_VALUE, min_index = -1; + + for (int v = 0; v < V; v++) + if (mstSet[v] == false && key[v] < min) { + min = key[v]; + min_index = v; + } + + return min_index; + } + + // A utility function to print the constructed MST stored in + // parent[] + void printMST(int parent[], int graph[][]) + { + System.out.println("Edge \tWeight"); + for (int i = 1; i < V; i++) + System.out.println(parent[i] + " - " + i + "\t" + graph[i][parent[i]]); + } + + // Function to construct and print MST for a graph represented + // using adjacency matrix representation + void primMST(int graph[][]) + { + // Array to store constructed MST + int parent[] = new int[V]; + + // Key values used to pick minimum weight edge in cut + int key[] = new int[V]; + + // To represent set of vertices included in MST + Boolean mstSet[] = new Boolean[V]; + + // Initialize all keys as INFINITE + for (int i = 0; i < V; i++) { + key[i] = Integer.MAX_VALUE; + mstSet[i] = false; + } + + // Always include first 1st vertex in MST. + key[0] = 0; // Make key 0 so that this vertex is + // picked as first vertex + parent[0] = -1; // First node is always root of MST + + // The MST will have V vertices + for (int count = 0; count < V - 1; count++) { + // Pick thd minimum key vertex from the set of vertices + // not yet included in MST + int u = minKey(key, mstSet); + + // Add the picked vertex to the MST Set + mstSet[u] = true; + + // Update key value and parent index of the adjacent + // vertices of the picked vertex. Consider only those + // vertices which are not yet included in MST + for (int v = 0; v < V; v++) + + // graph[u][v] is non zero only for adjacent vertices of m + // mstSet[v] is false for vertices not yet included in MST + // Update the key only if graph[u][v] is smaller than key[v] + if (graph[u][v] != 0 && mstSet[v] == false && graph[u][v] < key[v]) { + parent[v] = u; + key[v] = graph[u][v]; + } + } + + // print the constructed MST + printMST(parent, graph); + } + + public static void main(String[] args) + { + /* Let us create the following graph + 2 3 + (0)--(1)--(2) + | / \ | + 6| 8/ \5 |7 + | / \ | + (3)-------(4) + 9 */ + PrimsAlgo t = new PrimsAlgo(); + int graph[][] = new int[][] { { 0, 2, 0, 6, 0 }, + { 2, 0, 3, 8, 5 }, + { 0, 3, 0, 0, 7 }, + { 6, 8, 0, 0, 9 }, + { 0, 5, 7, 9, 0 } }; + + // Print the solution + t.primMST(graph); + } +} +//This code is contributed by Anilabha Baral diff --git a/GraphProblem/ShortestPathDijkstra.java b/GraphProblem/ShortestPathDijkstra.java new file mode 100644 index 0000000..ed6e55c --- /dev/null +++ b/GraphProblem/ShortestPathDijkstra.java @@ -0,0 +1,98 @@ +package GraphProblem; + +//A Java program for Dijkstra's single source shortest path algorithm. +//The program is for adjacency matrix representation of the graph +import java.util.*; +import java.lang.*; +import java.io.*; + +public class ShortestPathDijkstra { + // A utility function to find the vertex with minimum distance value, + // from the set of vertices not yet included in shortest path tree + static final int V = 9; + + int minDistance(int dist[], Boolean sptSet[]) { + // Initialize min value + int min = Integer.MAX_VALUE, min_index = -1; + + for (int v = 0; v < V; v++) + if (sptSet[v] == false && dist[v] <= min) { + min = dist[v]; + min_index = v; + } + + return min_index; + } + + // A utility function to print the constructed distance array + void printSolution(int dist[]) { + System.out.println("Vertex \t\t Distance from Source"); + for (int i = 0; i < V; i++) + System.out.println(i + " \t\t " + dist[i]); + } + + // Function that implements Dijkstra's single source shortest path + // algorithm for a graph represented using adjacency matrix + // representation + void dijkstra(int graph[][], int src) { + int dist[] = new int[V]; // The output array. dist[i] will hold + // the shortest distance from src to i + + // sptSet[i] will true if vertex i is included in shortest + // path tree or shortest distance from src to i is finalized + Boolean sptSet[] = new Boolean[V]; + + // Initialize all distances as INFINITE and stpSet[] as false + for (int i = 0; i < V; i++) { + dist[i] = Integer.MAX_VALUE; + sptSet[i] = false; + } + + // Distance of source vertex from itself is always 0 + dist[src] = 0; + + // Find shortest path for all vertices + for (int count = 0; count < V - 1; count++) { + // Pick the minimum distance vertex from the set of vertices + // not yet processed. u is always equal to src in first + // iteration. + int u = minDistance(dist, sptSet); + + // Mark the picked vertex as processed + sptSet[u] = true; + + // Update dist value of the adjacent vertices of the + // picked vertex. + for (int v = 0; v < V; v++) + + // Update dist[v] only if is not in sptSet, there is an + // edge from u to v, and total weight of path from src to + // v through u is smaller than current value of dist[v] + if (!sptSet[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] < dist[v]) + dist[v] = dist[u] + graph[u][v]; + } + + // print the constructed distance array + printSolution(dist); + } + + // Driver method + public static void main(String[] args) { + /* Let us create the example graph discussed above */ + + int graph[][] = new int[][] + { { 0, 4, 0, 0, 0, 0, 0, 8, 0 }, + { 4, 0, 8, 0, 0, 0, 0, 11, 0 }, + { 0, 8, 0, 7, 0, 4, 0, 0, 2 }, + { 0, 0, 7, 0, 9, 14, 0, 0, 0 }, + { 0, 0, 0, 9, 0, 10, 0, 0, 0 }, + { 0, 0, 4, 14, 10, 0, 2, 0, 0 }, + { 0, 0, 0, 0, 0, 2, 0, 1, 6 }, + { 8, 11, 0, 0, 0, 0, 1, 0, 7 }, + { 0, 0, 2, 0, 0, 0, 6, 7, 0 } }; + ShortestPathDijkstra t = new ShortestPathDijkstra(); + t.dijkstra(graph, 0); + } +} +//This code is contributed by Anilabha Baral +