From 66841dd0f6d17db772c96ad832c90543c29125ca Mon Sep 17 00:00:00 2001 From: saty-a Date: Sat, 7 Oct 2023 11:38:32 +0530 Subject: [PATCH] Add: algoritms in java --- .DS_Store | Bin 0 -> 10244 bytes Java/.DS_Store | Bin 0 -> 6148 bytes Java/Algorithms/Dijkstra.java | 186 +++++++++++++++++++++++++++++++ Java/Algorithms/KruskalsMST.java | 143 ++++++++++++++++++++++++ 4 files changed, 329 insertions(+) create mode 100644 .DS_Store create mode 100644 Java/.DS_Store create mode 100644 Java/Algorithms/Dijkstra.java create mode 100644 Java/Algorithms/KruskalsMST.java diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..7b6980c51517fc595a3b2b95e3e63827b9169f9f GIT binary patch literal 10244 zcmeHMU2oe|7=GP#ZPFI#)Nb5>urwio)Ri)6bcmZKZG{GGR7=G!_y|dyt|pEhY-gcV zMZE?71Al=_{sou(4DPvt=XsAaY{%iUAaPtduYLS}o#*{HJ7*%|G{@fCBCd$kaFedD z;iux_ciuDCLN@X`r~`SCj-=8TPg*jX;kE-70gHe|z#?D~un7DY5Wt$vtF~&W{j~^K z1S|s25nz9Cag*+4^wLmm9r)2L0O%ry^};ju0V?BWbT6ZqhN>uZn%#qwi8|R9!!hFc z?vfpJFQb=+8gX%qxHy?*C)=SoY8`T}vWv54sQtAFSOjJf;NE>x8WM^x!@~aE$5@En zd@S2?ihcc1f(Jp=>jqI5GAy$O?(IMI!js4njN{i+s+jCB9AR z!m|*(v7DhNP&=P{@X5s~!x?OyN+e-P&yOWNE3yx{K-zLNSLTnB%yq~F(A|?kQM=Ck zr`*h60#5{lMl#kDkR!ZJGVI`ENt#&XrEjS87_&@qc0$Qejx`edd`bE^fn+r1}}5x7}4xQnp(PeV)lInUC*R5i()~`qI^)rN35#(x|3v-W%DoH zQQ#-(&dzVn!nMWgOUt$8+G_3d)@d|prJZz~G&}L9d^?V!pgVo;bU*R?llJ=NeiWu1 zKkUaU;Cp?reD=f-y=c;m#-W#}Y|DJ8)obG%m+6R9?vFl>C5)=hJ@Hio+lZpJI&sD^oad7}wKqjwCHY z=pX?K(9~rB2tC{^{EE;y2z^0fSw4~nD3e2ktR;s<{Tk@+a)G`LZj`D#)nKP6V5Ur{ zMcvcV@e$}g##?yn>iE~18X@LDk9tVsQOOF*$;n%JO&)?bRx8xRWTveXeRAOg8_EDY z9!B|=;CoW7UDKziJ)fK`u7gYiwX%4seW(7)5-j+B6FjDgPSjfu4U1@*M$F??&ZbHe zBa`=YLz@7xc2QoY7+syYJHG{L#D333Z0R3(iF=-R4W2P`*usYJn=O&;GcLwU5zWih zNhqAat9eUwOd)E>@)?v zw@P~3g{m}f#CJ}n7j)fFOal1C>YL_40zX;z6&jf33%}-~@*!%Lm4$^KvuXlABHDt+ z0DrE2bCI1L`3CxjxQQX_h_gPyJNwHRewb`vSD`j8pm{kiY9@B3^W=FbN!{eB#88+O zd9QC}Ub8nG!PW>g##j$}xRjbsQMq_(oQt{=wak9Tr8~tNGb<=8#dCXD!LJo8;%Dkj z0$*4mvnvm}RY7LDqFHJYun1TLECN@6z%^sTT?IXy|NsA2;E6S15wHmSTL?Id2d#r9 ztUGf&;90wi`%B!s$aiU|ir`0&<3aT}9xptOe*-spcSw2Rc`u`vhGGQQ)&FOJ-Tzk} Oo7(+9_A396{r_L+lyIs5 literal 0 HcmV?d00001 diff --git a/Java/.DS_Store b/Java/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..407e648563f6e81528e14a9d9d8f8d57a7538621 GIT binary patch literal 6148 zcmeHKO;5r=5S>MYA~E5h(c>mwiK2;u@lp^EUairC8l*z7v33b9av&tV>YwrGKk@JA z%d&b)rSHv0hpqA~1j1C#*3K_|= settled; + private PriorityQueue pq; + // Number of vertices + private int V; + List > adj; + + // Constructor of this class + public Dijkstra(int V) + { + + // This keyword refers to current object itself + this.V = V; + dist = new int[V]; + settled = new HashSet(); + pq = new PriorityQueue(V, new Node()); + } + + // Method 1 + // Dijkstra's Algorithm + public void dijkstra(List > adj, int src) + { + this.adj = adj; + + for (int i = 0; i < V; i++) + dist[i] = Integer.MAX_VALUE; + + // Add source node to the priority queue + pq.add(new Node(src, 0)); + + // Distance to the source is 0 + dist[src] = 0; + + while (settled.size() != V) { + + // Terminating condition check when + // the priority queue is empty, return + if (pq.isEmpty()) + return; + + // Removing the minimum distance node + // from the priority queue + int u = pq.remove().node; + + // Adding the node whose distance is + // finalized + if (settled.contains(u)) + + // Continue keyword skips execution for + // following check + continue; + + // We don't have to call e_Neighbors(u) + // if u is already present in the settled set. + settled.add(u); + + e_Neighbours(u); + } + } + + // Method 2 + // To process all the neighbours + // of the passed node + private void e_Neighbours(int u) + { + + int edgeDistance = -1; + int newDistance = -1; + + // All the neighbors of v + for (int i = 0; i < adj.get(u).size(); i++) { + Node v = adj.get(u).get(i); + + // If current node hasn't already been processed + if (!settled.contains(v.node)) { + edgeDistance = v.cost; + newDistance = dist[u] + edgeDistance; + + // If new distance is cheaper in cost + if (newDistance < dist[v.node]) + dist[v.node] = newDistance; + + // Add the current node to the queue + pq.add(new Node(v.node, dist[v.node])); + } + } + } + + // Main driver method + public static void main(String arg[]) + { + + int V = 5; + int source = 0; + + // Adjacency list representation of the + // connected edges by declaring List class object + // Declaring object of type List + List > adj + = new ArrayList >(); + + // Initialize list for every node + for (int i = 0; i < V; i++) { + List item = new ArrayList(); + adj.add(item); + } + + // Inputs for the GFG(dpq) graph + adj.get(0).add(new Node(1, 9)); + adj.get(0).add(new Node(2, 6)); + adj.get(0).add(new Node(3, 5)); + adj.get(0).add(new Node(4, 3)); + + adj.get(2).add(new Node(1, 2)); + adj.get(2).add(new Node(3, 4)); + + // Calculating the single source shortest path + Dijkstra dpq = new Dijkstra(V); + dpq.dijkstra(adj, source); + + // Printing the shortest path to all the nodes + // from the source node + System.out.println("The shorted path from node :"); + + for (int i = 0; i < dpq.dist.length; i++) + System.out.println(source + " to " + i + " is " + + dpq.dist[i]); + } +} + +// Class 2 +// Helper class implementing Comparator interface +// Representing a node in the graph +class Node implements Comparator { + + // Member variables of this class + public int node; + public int cost; + + // Constructors of this class + + // Constructor 1 + public Node() {} + + // Constructor 2 + public Node(int node, int cost) + { + + // This keyword refers to current instance itself + this.node = node; + this.cost = cost; + } + + // Method 1 + @Override public int compare(Node node1, Node node2) + { + + if (node1.cost < node2.cost) + return -1; + + if (node1.cost > node2.cost) + return 1; + + return 0; + } +} + +/// The Output will be +/* +The shorted path from node : +0 to 0 is 0 +0 to 1 is 8 +0 to 2 is 6 +0 to 3 is 5 +0 to 4 is 3 + */ \ No newline at end of file diff --git a/Java/Algorithms/KruskalsMST.java b/Java/Algorithms/KruskalsMST.java new file mode 100644 index 0000000..e4c1af1 --- /dev/null +++ b/Java/Algorithms/KruskalsMST.java @@ -0,0 +1,143 @@ +// Java program for Kruskal's algorithm + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +public class KruskalsMST { + + // Defines edge structure + static class Edge { + int src, dest, weight; + + public Edge(int src, int dest, int weight) + { + this.src = src; + this.dest = dest; + this.weight = weight; + } + } + + // Defines subset element structure + static class Subset { + int parent, rank; + + public Subset(int parent, int rank) + { + this.parent = parent; + this.rank = rank; + } + } + + // Starting point of program execution + public static void main(String[] args) + { + int V = 4; + List graphEdges = new ArrayList( + List.of(new Edge(0, 1, 10), new Edge(0, 2, 6), + new Edge(0, 3, 5), new Edge(1, 3, 15), + new Edge(2, 3, 4))); + + // Sort the edges in non-decreasing order + // (increasing with repetition allowed) + graphEdges.sort(new Comparator() { + @Override public int compare(Edge o1, Edge o2) + { + return o1.weight - o2.weight; + } + }); + + kruskals(V, graphEdges); + } + + // Function to find the MST + private static void kruskals(int V, List edges) + { + int j = 0; + int noOfEdges = 0; + + // Allocate memory for creating V subsets + Subset subsets[] = new Subset[V]; + + // Allocate memory for results + Edge results[] = new Edge[V]; + + // Create V subsets with single elements + for (int i = 0; i < V; i++) { + subsets[i] = new Subset(i, 0); + } + + // Number of edges to be taken is equal to V-1 + while (noOfEdges < V - 1) { + + // Pick the smallest edge. And increment + // the index for next iteration + Edge nextEdge = edges.get(j); + int x = findRoot(subsets, nextEdge.src); + int y = findRoot(subsets, nextEdge.dest); + + // If including this edge doesn't cause cycle, + // include it in result and increment the index + // of result for next edge + if (x != y) { + results[noOfEdges] = nextEdge; + union(subsets, x, y); + noOfEdges++; + } + + j++; + } + + // Print the contents of result[] to display the + // built MST + System.out.println( + "Following are the edges of the constructed MST:"); + int minCost = 0; + for (int i = 0; i < noOfEdges; i++) { + System.out.println(results[i].src + " -- " + + results[i].dest + " == " + + results[i].weight); + minCost += results[i].weight; + } + System.out.println("Total cost of MST: " + minCost); + } + + // Function to unite two disjoint sets + private static void union(Subset[] subsets, int x, + int y) + { + int rootX = findRoot(subsets, x); + int rootY = findRoot(subsets, y); + + if (subsets[rootY].rank < subsets[rootX].rank) { + subsets[rootY].parent = rootX; + } + else if (subsets[rootX].rank + < subsets[rootY].rank) { + subsets[rootX].parent = rootY; + } + else { + subsets[rootY].parent = rootX; + subsets[rootX].rank++; + } + } + + // Function to find parent of a set + private static int findRoot(Subset[] subsets, int i) + { + if (subsets[i].parent == i) + return subsets[i].parent; + + subsets[i].parent + = findRoot(subsets, subsets[i].parent); + return subsets[i].parent; + } +} + +// Output will be like : +/* +2 -- 3 == 4 +0 -- 3 == 5 +0 -- 1 == 10 +Minimum Cost Spanning Tree: 19 + */