mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-27 06:23:08 +08:00
Format code with prettier (#3375)
This commit is contained in:
@ -8,6 +8,7 @@ import java.util.*;
|
||||
public class A_Star {
|
||||
|
||||
private static class Graph {
|
||||
|
||||
// Graph's structure can be changed only applying changes to this class.
|
||||
|
||||
private ArrayList<ArrayList<Edge>> graph;
|
||||
@ -26,8 +27,10 @@ public class A_Star {
|
||||
|
||||
// Graph is bidirectional, for just one direction remove second instruction of this method.
|
||||
private void addEdge(Edge edge) {
|
||||
this.graph.get(edge.getFrom()).add(new Edge(edge.getFrom(), edge.getTo(), edge.getWeight()));
|
||||
this.graph.get(edge.getTo()).add(new Edge(edge.getTo(), edge.getFrom(), edge.getWeight()));
|
||||
this.graph.get(edge.getFrom())
|
||||
.add(new Edge(edge.getFrom(), edge.getTo(), edge.getWeight()));
|
||||
this.graph.get(edge.getTo())
|
||||
.add(new Edge(edge.getTo(), edge.getFrom(), edge.getWeight()));
|
||||
}
|
||||
}
|
||||
|
||||
@ -63,7 +66,11 @@ public class A_Star {
|
||||
private ArrayList<Integer> path; // list of visited nodes in this path.
|
||||
private int estimated; // heuristic value associated to the last node od the path (current node).
|
||||
|
||||
public PathAndDistance(int distance, ArrayList<Integer> path, int estimated) {
|
||||
public PathAndDistance(
|
||||
int distance,
|
||||
ArrayList<Integer> path,
|
||||
int estimated
|
||||
) {
|
||||
this.distance = distance;
|
||||
this.path = path;
|
||||
this.estimated = estimated;
|
||||
@ -84,16 +91,24 @@ public class A_Star {
|
||||
private void printSolution() {
|
||||
if (this.path != null) {
|
||||
System.out.println(
|
||||
"Optimal path: " + this.path + ", distance: " + this.distance);
|
||||
"Optimal path: " +
|
||||
this.path +
|
||||
", distance: " +
|
||||
this.distance
|
||||
);
|
||||
} else {
|
||||
System.out.println("There is no path available to connect the points");
|
||||
System.out.println(
|
||||
"There is no path available to connect the points"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void initializeGraph(Graph graph, ArrayList<Integer> data) {
|
||||
for (int i = 0; i < data.size(); i += 4) {
|
||||
graph.addEdge(new Edge(data.get(i), data.get(i + 1), data.get(i + 2)));
|
||||
graph.addEdge(
|
||||
new Edge(data.get(i), data.get(i + 1), data.get(i + 2))
|
||||
);
|
||||
}
|
||||
/*
|
||||
.x. node
|
||||
@ -127,30 +142,146 @@ public class A_Star {
|
||||
public static void main(String[] args) {
|
||||
// heuristic function optimistic values
|
||||
int[] heuristic = {
|
||||
366, 0, 160, 242, 161, 178, 77, 151, 226, 244, 241, 234, 380, 98, 193, 253, 329, 80, 199, 374
|
||||
366,
|
||||
0,
|
||||
160,
|
||||
242,
|
||||
161,
|
||||
178,
|
||||
77,
|
||||
151,
|
||||
226,
|
||||
244,
|
||||
241,
|
||||
234,
|
||||
380,
|
||||
98,
|
||||
193,
|
||||
253,
|
||||
329,
|
||||
80,
|
||||
199,
|
||||
374,
|
||||
};
|
||||
|
||||
Graph graph = new Graph(20);
|
||||
ArrayList<Integer> graphData
|
||||
= new ArrayList<>(
|
||||
Arrays.asList(
|
||||
0, 19, 75, null, 0, 15, 140, null, 0, 16, 118, null, 19, 12, 71, null, 12, 15, 151,
|
||||
null, 16, 9, 111, null, 9, 10, 70, null, 10, 3, 75, null, 3, 2, 120, null, 2, 14,
|
||||
146, null, 2, 13, 138, null, 2, 6, 115, null, 15, 14, 80, null, 15, 5, 99, null, 14,
|
||||
13, 97, null, 5, 1, 211, null, 13, 1, 101, null, 6, 1, 160, null, 1, 17, 85, null,
|
||||
17, 7, 98, null, 7, 4, 86, null, 17, 18, 142, null, 18, 8, 92, null, 8, 11, 87));
|
||||
ArrayList<Integer> graphData = new ArrayList<>(
|
||||
Arrays.asList(
|
||||
0,
|
||||
19,
|
||||
75,
|
||||
null,
|
||||
0,
|
||||
15,
|
||||
140,
|
||||
null,
|
||||
0,
|
||||
16,
|
||||
118,
|
||||
null,
|
||||
19,
|
||||
12,
|
||||
71,
|
||||
null,
|
||||
12,
|
||||
15,
|
||||
151,
|
||||
null,
|
||||
16,
|
||||
9,
|
||||
111,
|
||||
null,
|
||||
9,
|
||||
10,
|
||||
70,
|
||||
null,
|
||||
10,
|
||||
3,
|
||||
75,
|
||||
null,
|
||||
3,
|
||||
2,
|
||||
120,
|
||||
null,
|
||||
2,
|
||||
14,
|
||||
146,
|
||||
null,
|
||||
2,
|
||||
13,
|
||||
138,
|
||||
null,
|
||||
2,
|
||||
6,
|
||||
115,
|
||||
null,
|
||||
15,
|
||||
14,
|
||||
80,
|
||||
null,
|
||||
15,
|
||||
5,
|
||||
99,
|
||||
null,
|
||||
14,
|
||||
13,
|
||||
97,
|
||||
null,
|
||||
5,
|
||||
1,
|
||||
211,
|
||||
null,
|
||||
13,
|
||||
1,
|
||||
101,
|
||||
null,
|
||||
6,
|
||||
1,
|
||||
160,
|
||||
null,
|
||||
1,
|
||||
17,
|
||||
85,
|
||||
null,
|
||||
17,
|
||||
7,
|
||||
98,
|
||||
null,
|
||||
7,
|
||||
4,
|
||||
86,
|
||||
null,
|
||||
17,
|
||||
18,
|
||||
142,
|
||||
null,
|
||||
18,
|
||||
8,
|
||||
92,
|
||||
null,
|
||||
8,
|
||||
11,
|
||||
87
|
||||
)
|
||||
);
|
||||
initializeGraph(graph, graphData);
|
||||
|
||||
PathAndDistance solution = aStar(3, 1, graph, heuristic);
|
||||
solution.printSolution();
|
||||
}
|
||||
|
||||
public static PathAndDistance aStar(int from, int to, Graph graph, int[] heuristic) {
|
||||
public static PathAndDistance aStar(
|
||||
int from,
|
||||
int to,
|
||||
Graph graph,
|
||||
int[] heuristic
|
||||
) {
|
||||
// nodes are prioritised by the less value of the current distance of their paths, and the
|
||||
// estimated value
|
||||
// given by the heuristic function to reach the destination point from the current point.
|
||||
PriorityQueue<PathAndDistance> queue
|
||||
= new PriorityQueue<>(Comparator.comparingInt(a -> (a.getDistance() + a.getEstimated())));
|
||||
PriorityQueue<PathAndDistance> queue = new PriorityQueue<>(
|
||||
Comparator.comparingInt(a -> (a.getDistance() + a.getEstimated()))
|
||||
);
|
||||
|
||||
// dummy data to start the algorithm from the beginning point
|
||||
queue.add(new PathAndDistance(0, new ArrayList<>(List.of(from)), 0));
|
||||
@ -159,26 +290,33 @@ public class A_Star {
|
||||
PathAndDistance currentData = new PathAndDistance(-1, null, -1);
|
||||
while (!queue.isEmpty() && !solutionFound) {
|
||||
currentData = queue.poll(); // first in the queue, best node so keep exploring.
|
||||
int currentPosition
|
||||
= currentData.getPath().get(currentData.getPath().size() - 1); // current node.
|
||||
int currentPosition = currentData
|
||||
.getPath()
|
||||
.get(currentData.getPath().size() - 1); // current node.
|
||||
if (currentPosition == to) {
|
||||
solutionFound = true;
|
||||
} else {
|
||||
for (Edge edge : graph.getNeighbours(currentPosition)) {
|
||||
if (!currentData.getPath().contains(edge.getTo())) { // Avoid Cycles
|
||||
ArrayList<Integer> updatedPath = new ArrayList<>(currentData.getPath());
|
||||
ArrayList<Integer> updatedPath = new ArrayList<>(
|
||||
currentData.getPath()
|
||||
);
|
||||
updatedPath.add(edge.getTo()); // Add the new node to the path, update the distance,
|
||||
// and the heuristic function value associated to that path.
|
||||
queue.add(
|
||||
new PathAndDistance(
|
||||
currentData.getDistance() + edge.getWeight(),
|
||||
updatedPath,
|
||||
heuristic[edge.getTo()]));
|
||||
new PathAndDistance(
|
||||
currentData.getDistance() + edge.getWeight(),
|
||||
updatedPath,
|
||||
heuristic[edge.getTo()]
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return (solutionFound) ? currentData : new PathAndDistance(-1, null, -1);
|
||||
return (solutionFound)
|
||||
? currentData
|
||||
: new PathAndDistance(-1, null, -1);
|
||||
// Out of while loop, if there is a solution, the current Data stores the optimal path, and its
|
||||
// distance
|
||||
}
|
||||
|
@ -3,7 +3,7 @@ package com.thealgorithms.datastructures.graphs;
|
||||
import java.util.*;
|
||||
|
||||
class BellmanFord /*Implementation of Bellman ford to detect negative cycles. Graph accepts inputs in form of edges which have
|
||||
start vertex, end vertex and weights. Vertices should be labelled with a number between 0 and total number of vertices-1,both inclusive*/ {
|
||||
start vertex, end vertex and weights. Vertices should be labelled with a number between 0 and total number of vertices-1,both inclusive*/{
|
||||
|
||||
int vertex, edge;
|
||||
private Edge edges[];
|
||||
@ -37,8 +37,7 @@ start vertex, end vertex and weights. Vertices should be labelled with a number
|
||||
* @param i Current vertex under consideration
|
||||
*/
|
||||
void printPath(int p[], int i) {
|
||||
if (p[i] == -1) // Found the path back to parent
|
||||
{
|
||||
if (p[i] == -1) { // Found the path back to parent
|
||||
return;
|
||||
}
|
||||
printPath(p, p[i]);
|
||||
@ -50,10 +49,7 @@ start vertex, end vertex and weights. Vertices should be labelled with a number
|
||||
obj.go();
|
||||
}
|
||||
|
||||
public void
|
||||
go() // Interactive run for understanding the class first time. Assumes source vertex is 0 and
|
||||
// shows distance to all vertices
|
||||
{
|
||||
public void go() { // shows distance to all vertices // Interactive run for understanding the class first time. Assumes source vertex is 0 and
|
||||
Scanner sc = new Scanner(System.in); // Grab scanner object for user input
|
||||
int i, v, e, u, ve, w, j, neg = 0;
|
||||
System.out.println("Enter no. of vertices and edges please");
|
||||
@ -67,8 +63,7 @@ start vertex, end vertex and weights. Vertices should be labelled with a number
|
||||
w = sc.nextInt();
|
||||
arr[i] = new Edge(u, ve, w);
|
||||
}
|
||||
int dist[]
|
||||
= new int[v]; // Distance array for holding the finalized shortest path distance between source
|
||||
int dist[] = new int[v]; // Distance array for holding the finalized shortest path distance between source
|
||||
// and all vertices
|
||||
int p[] = new int[v]; // Parent array for holding the paths
|
||||
for (i = 0; i < v; i++) {
|
||||
@ -78,8 +73,10 @@ start vertex, end vertex and weights. Vertices should be labelled with a number
|
||||
p[0] = -1;
|
||||
for (i = 0; i < v - 1; i++) {
|
||||
for (j = 0; j < e; j++) {
|
||||
if ((int) dist[arr[j].u] != Integer.MAX_VALUE
|
||||
&& dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
|
||||
if (
|
||||
(int) dist[arr[j].u] != Integer.MAX_VALUE &&
|
||||
dist[arr[j].v] > dist[arr[j].u] + arr[j].w
|
||||
) {
|
||||
dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update
|
||||
p[arr[j].v] = arr[j].u;
|
||||
}
|
||||
@ -87,14 +84,16 @@ start vertex, end vertex and weights. Vertices should be labelled with a number
|
||||
}
|
||||
// Final cycle for negative checking
|
||||
for (j = 0; j < e; j++) {
|
||||
if ((int) dist[arr[j].u] != Integer.MAX_VALUE && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
|
||||
if (
|
||||
(int) dist[arr[j].u] != Integer.MAX_VALUE &&
|
||||
dist[arr[j].v] > dist[arr[j].u] + arr[j].w
|
||||
) {
|
||||
neg = 1;
|
||||
System.out.println("Negative cycle");
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (neg == 0) // Go ahead and show results of computation
|
||||
{
|
||||
if (neg == 0) { // Go ahead and show results of computation
|
||||
System.out.println("Distances are: ");
|
||||
for (i = 0; i < v; i++) {
|
||||
System.out.println(i + " " + dist[i]);
|
||||
@ -114,15 +113,9 @@ start vertex, end vertex and weights. Vertices should be labelled with a number
|
||||
* @param end Ending vertex
|
||||
* @param Edge Array of edges
|
||||
*/
|
||||
public void show(
|
||||
int source,
|
||||
int end,
|
||||
Edge arr[]) // Just shows results of computation, if graph is passed to it. The graph should
|
||||
// be created by using addEdge() method and passed by calling getEdgeArray() method
|
||||
{
|
||||
public void show(int source, int end, Edge arr[]) { // be created by using addEdge() method and passed by calling getEdgeArray() method // Just shows results of computation, if graph is passed to it. The graph should
|
||||
int i, j, v = vertex, e = edge, neg = 0;
|
||||
double dist[]
|
||||
= new double[v]; // Distance array for holding the finalized shortest path distance between source
|
||||
double dist[] = new double[v]; // Distance array for holding the finalized shortest path distance between source
|
||||
// and all vertices
|
||||
int p[] = new int[v]; // Parent array for holding the paths
|
||||
for (i = 0; i < v; i++) {
|
||||
@ -132,8 +125,10 @@ start vertex, end vertex and weights. Vertices should be labelled with a number
|
||||
p[source] = -1;
|
||||
for (i = 0; i < v - 1; i++) {
|
||||
for (j = 0; j < e; j++) {
|
||||
if ((int) dist[arr[j].u] != Integer.MAX_VALUE
|
||||
&& dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
|
||||
if (
|
||||
(int) dist[arr[j].u] != Integer.MAX_VALUE &&
|
||||
dist[arr[j].v] > dist[arr[j].u] + arr[j].w
|
||||
) {
|
||||
dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update
|
||||
p[arr[j].v] = arr[j].u;
|
||||
}
|
||||
@ -141,14 +136,16 @@ start vertex, end vertex and weights. Vertices should be labelled with a number
|
||||
}
|
||||
// Final cycle for negative checking
|
||||
for (j = 0; j < e; j++) {
|
||||
if ((int) dist[arr[j].u] != Integer.MAX_VALUE && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
|
||||
if (
|
||||
(int) dist[arr[j].u] != Integer.MAX_VALUE &&
|
||||
dist[arr[j].v] > dist[arr[j].u] + arr[j].w
|
||||
) {
|
||||
neg = 1;
|
||||
System.out.println("Negative cycle");
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (neg == 0) // Go ahead and show results of computaion
|
||||
{
|
||||
if (neg == 0) { // Go ahead and show results of computaion
|
||||
System.out.println("Distance is: " + dist[end]);
|
||||
System.out.println("Path followed:");
|
||||
System.out.print(source + " ");
|
||||
@ -162,8 +159,7 @@ start vertex, end vertex and weights. Vertices should be labelled with a number
|
||||
* @param y End vertex
|
||||
* @param z Weight
|
||||
*/
|
||||
public void addEdge(int x, int y, int z) // Adds unidirectional edge
|
||||
{
|
||||
public void addEdge(int x, int y, int z) { // Adds unidirectional edge
|
||||
edges[index++] = new Edge(x, y, z);
|
||||
}
|
||||
|
||||
|
@ -16,7 +16,12 @@ import java.util.Arrays;
|
||||
*/
|
||||
public class BipartiteGrapfDFS {
|
||||
|
||||
private static boolean bipartite(int V, ArrayList<ArrayList<Integer>> adj, int[] color, int node) {
|
||||
private static boolean bipartite(
|
||||
int V,
|
||||
ArrayList<ArrayList<Integer>> adj,
|
||||
int[] color,
|
||||
int node
|
||||
) {
|
||||
if (color[node] == -1) {
|
||||
color[node] = 1;
|
||||
}
|
||||
@ -33,7 +38,10 @@ public class BipartiteGrapfDFS {
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean isBipartite(int V, ArrayList<ArrayList<Integer>> adj) {
|
||||
public static boolean isBipartite(
|
||||
int V,
|
||||
ArrayList<ArrayList<Integer>> adj
|
||||
) {
|
||||
// Code here
|
||||
int[] color = new int[V + 1];
|
||||
Arrays.fill(color, -1);
|
||||
@ -49,7 +57,9 @@ public class BipartiteGrapfDFS {
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
|
||||
BufferedReader read = new BufferedReader(
|
||||
new InputStreamReader(System.in)
|
||||
);
|
||||
int t = Integer.parseInt(read.readLine().trim());
|
||||
while (t-- > 0) {
|
||||
String[] S = read.readLine().trim().split(" ");
|
||||
|
@ -137,7 +137,11 @@ public class ConnectedComponent {
|
||||
graphInts.addEdge(8, 10);
|
||||
graphInts.addEdge(10, 8);
|
||||
|
||||
System.out.println("Amount of different char-graphs: " + graphChars.countGraphs());
|
||||
System.out.println("Amount of different int-graphs: " + graphInts.countGraphs());
|
||||
System.out.println(
|
||||
"Amount of different char-graphs: " + graphChars.countGraphs()
|
||||
);
|
||||
System.out.println(
|
||||
"Amount of different int-graphs: " + graphInts.countGraphs()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
@ -24,7 +24,9 @@ class Cycle {
|
||||
visited[i] = false;
|
||||
}
|
||||
|
||||
System.out.println("Enter the details of each edges <Start Node> <End Node>");
|
||||
System.out.println(
|
||||
"Enter the details of each edges <Start Node> <End Node>"
|
||||
);
|
||||
|
||||
for (int i = 0; i < edges; i++) {
|
||||
int start, end;
|
||||
|
@ -40,13 +40,17 @@ class dijkstras {
|
||||
dist[src] = 0;
|
||||
|
||||
for (int c = 0; c < k - 1; c++) {
|
||||
|
||||
int u = minDist(dist, Set);
|
||||
|
||||
Set[u] = true;
|
||||
|
||||
for (int v = 0; v < k; v++) {
|
||||
if (!Set[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] < dist[v]) {
|
||||
if (
|
||||
!Set[v] &&
|
||||
graph[u][v] != 0 &&
|
||||
dist[u] != Integer.MAX_VALUE &&
|
||||
dist[u] + graph[u][v] < dist[v]
|
||||
) {
|
||||
dist[v] = dist[u] + graph[u][v];
|
||||
}
|
||||
}
|
||||
@ -56,21 +60,21 @@ class dijkstras {
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
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}};
|
||||
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 },
|
||||
};
|
||||
dijkstras t = new dijkstras();
|
||||
t.dijkstra(graph, 0);
|
||||
}//main
|
||||
|
||||
}//djikstras
|
||||
|
||||
} //main
|
||||
} //djikstras
|
||||
/*
|
||||
OUTPUT :
|
||||
Vertex Distance
|
||||
|
@ -9,31 +9,42 @@ public class FloydWarshall {
|
||||
public static final int INFINITY = 999;
|
||||
|
||||
public FloydWarshall(int numberofvertices) {
|
||||
DistanceMatrix
|
||||
= new int[numberofvertices + 1][numberofvertices
|
||||
+ 1]; // stores the value of distance from all the possible path form the source
|
||||
DistanceMatrix = new int[numberofvertices + 1][numberofvertices + 1]; // stores the value of distance from all the possible path form the source
|
||||
// vertex to destination vertex
|
||||
// The matrix is initialized with 0's by default
|
||||
this.numberofvertices = numberofvertices;
|
||||
}
|
||||
|
||||
public void floydwarshall(
|
||||
int AdjacencyMatrix[][]) // calculates all the distances from source to destination vertex
|
||||
{
|
||||
public void floydwarshall(int AdjacencyMatrix[][]) { // calculates all the distances from source to destination vertex
|
||||
for (int source = 1; source <= numberofvertices; source++) {
|
||||
for (int destination = 1; destination <= numberofvertices; destination++) {
|
||||
DistanceMatrix[source][destination] = AdjacencyMatrix[source][destination];
|
||||
for (
|
||||
int destination = 1;
|
||||
destination <= numberofvertices;
|
||||
destination++
|
||||
) {
|
||||
DistanceMatrix[source][destination] =
|
||||
AdjacencyMatrix[source][destination];
|
||||
}
|
||||
}
|
||||
for (int intermediate = 1; intermediate <= numberofvertices; intermediate++) {
|
||||
for (
|
||||
int intermediate = 1;
|
||||
intermediate <= numberofvertices;
|
||||
intermediate++
|
||||
) {
|
||||
for (int source = 1; source <= numberofvertices; source++) {
|
||||
for (int destination = 1; destination <= numberofvertices; destination++) {
|
||||
if (DistanceMatrix[source][intermediate] + DistanceMatrix[intermediate][destination]
|
||||
< DistanceMatrix[source][destination]) // if the new distance calculated is less then the earlier shortest
|
||||
// calculated distance it get replaced as new shortest distance
|
||||
{
|
||||
for (
|
||||
int destination = 1;
|
||||
destination <= numberofvertices;
|
||||
destination++
|
||||
) {
|
||||
if (
|
||||
DistanceMatrix[source][intermediate] +
|
||||
DistanceMatrix[intermediate][destination] <
|
||||
DistanceMatrix[source][destination]
|
||||
= DistanceMatrix[source][intermediate] + DistanceMatrix[intermediate][destination];
|
||||
) { // calculated distance it get replaced as new shortest distance // if the new distance calculated is less then the earlier shortest
|
||||
DistanceMatrix[source][destination] =
|
||||
DistanceMatrix[source][intermediate] +
|
||||
DistanceMatrix[intermediate][destination];
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -44,7 +55,11 @@ public class FloydWarshall {
|
||||
System.out.println();
|
||||
for (int source = 1; source <= numberofvertices; source++) {
|
||||
System.out.print(source + "\t");
|
||||
for (int destination = 1; destination <= numberofvertices; destination++) {
|
||||
for (
|
||||
int destination = 1;
|
||||
destination <= numberofvertices;
|
||||
destination++
|
||||
) {
|
||||
System.out.print(DistanceMatrix[source][destination] + "\t");
|
||||
}
|
||||
System.out.println();
|
||||
@ -55,10 +70,15 @@ public class FloydWarshall {
|
||||
Scanner scan = new Scanner(System.in);
|
||||
System.out.println("Enter the number of vertices");
|
||||
int numberOfVertices = scan.nextInt();
|
||||
int[][] adjacencyMatrix = new int[numberOfVertices + 1][numberOfVertices + 1];
|
||||
int[][] adjacencyMatrix = new int[numberOfVertices +
|
||||
1][numberOfVertices + 1];
|
||||
System.out.println("Enter the Weighted Matrix for the graph");
|
||||
for (int source = 1; source <= numberOfVertices; source++) {
|
||||
for (int destination = 1; destination <= numberOfVertices; destination++) {
|
||||
for (
|
||||
int destination = 1;
|
||||
destination <= numberOfVertices;
|
||||
destination++
|
||||
) {
|
||||
adjacencyMatrix[source][destination] = scan.nextInt();
|
||||
if (source == destination) {
|
||||
adjacencyMatrix[source][destination] = 0;
|
||||
|
@ -12,33 +12,32 @@ public class HamiltonianCycle {
|
||||
|
||||
/**
|
||||
* Find hamiltonian cycle for given graph G(V,E)
|
||||
* @param graph Adjacency matrix of a graph G(V, E)
|
||||
* @param graph Adjacency matrix of a graph G(V, E)
|
||||
* for which hamiltonian path is to be found
|
||||
* @return Array containing hamiltonian cycle
|
||||
* @return Array containing hamiltonian cycle
|
||||
* else returns 1D array with value -1.
|
||||
*/
|
||||
public int[] findHamiltonianCycle(int[][] graph){
|
||||
public int[] findHamiltonianCycle(int[][] graph) {
|
||||
this.V = graph.length;
|
||||
this.cycle = new int[this.V+1];
|
||||
this.cycle = new int[this.V + 1];
|
||||
|
||||
//Initialize path array with -1 value
|
||||
for(int i=0 ; i<this.cycle.length ; i++) {
|
||||
for (int i = 0; i < this.cycle.length; i++) {
|
||||
this.cycle[i] = -1;
|
||||
}
|
||||
|
||||
this.graph = graph;
|
||||
this.graph = graph;
|
||||
|
||||
this.cycle[0] = 0;
|
||||
this.pathCount = 1;
|
||||
if(!isPathFound(0)) {
|
||||
for(int i=0 ; i<this.cycle.length ; i++) {
|
||||
this.pathCount = 1;
|
||||
if (!isPathFound(0)) {
|
||||
for (int i = 0; i < this.cycle.length; i++) {
|
||||
this.cycle[i] = -1;
|
||||
}
|
||||
} else {
|
||||
this.cycle[this.cycle.length - 1] = this.cycle[0];
|
||||
}
|
||||
else {
|
||||
this.cycle[this.cycle.length-1] = this.cycle[0];
|
||||
}
|
||||
|
||||
|
||||
return cycle;
|
||||
}
|
||||
|
||||
@ -57,13 +56,13 @@ public class HamiltonianCycle {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (int v = 0; v < this.V; v++){
|
||||
for (int v = 0; v < this.V; v++) {
|
||||
/** if connected **/
|
||||
if (this.graph[vertex][v] == 1 ){
|
||||
/** add to path **/
|
||||
this.cycle[this.pathCount++] = v;
|
||||
if (this.graph[vertex][v] == 1) {
|
||||
/** add to path **/
|
||||
this.cycle[this.pathCount++] = v;
|
||||
|
||||
/** remove connection **/
|
||||
/** remove connection **/
|
||||
this.graph[vertex][v] = 0;
|
||||
this.graph[v][vertex] = 0;
|
||||
|
||||
@ -81,14 +80,13 @@ public class HamiltonianCycle {
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** function to check if path is already selected
|
||||
* Check if path is already selected
|
||||
* @param vertex Starting vertex
|
||||
* @param vertex Starting vertex
|
||||
*/
|
||||
public boolean isPresent(int vertex){
|
||||
|
||||
public boolean isPresent(int vertex) {
|
||||
for (int i = 0; i < pathCount - 1; i++) {
|
||||
if (cycle[i] == vertex) {
|
||||
return true;
|
||||
|
@ -1,12 +1,12 @@
|
||||
package com.thealgorithms.datastructures.graphs;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Map;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.HashMap;
|
||||
import java.util.Set;
|
||||
import java.util.Queue;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Map;
|
||||
import java.util.Queue;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* An algorithm that sorts a graph in toplogical order.
|
||||
@ -124,7 +124,6 @@ class TopologicalSort<E extends Comparable<E>> {
|
||||
}
|
||||
|
||||
return answer;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@ -134,7 +133,6 @@ class TopologicalSort<E extends Comparable<E>> {
|
||||
public class KahnsAlgorithm {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
//Graph definition and initialization
|
||||
AdjacencyList<String> graph = new AdjacencyList<>();
|
||||
graph.addEdge("a", "b");
|
||||
|
@ -30,7 +30,12 @@ public class Kruskal {
|
||||
}
|
||||
}
|
||||
|
||||
private static void addEdge(HashSet<Edge>[] graph, int from, int to, int weight) {
|
||||
private static void addEdge(
|
||||
HashSet<Edge>[] graph,
|
||||
int from,
|
||||
int to,
|
||||
int weight
|
||||
) {
|
||||
graph[from].add(new Edge(from, to, weight));
|
||||
}
|
||||
|
||||
@ -53,7 +58,9 @@ public class Kruskal {
|
||||
System.out.println("Initial Graph: ");
|
||||
for (int i = 0; i < graph.length; i++) {
|
||||
for (Edge edge : graph[i]) {
|
||||
System.out.println(i + " <-- weight " + edge.weight + " --> " + edge.to);
|
||||
System.out.println(
|
||||
i + " <-- weight " + edge.weight + " --> " + edge.to
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -63,7 +70,9 @@ public class Kruskal {
|
||||
System.out.println("\nMinimal Graph: ");
|
||||
for (int i = 0; i < solGraph.length; i++) {
|
||||
for (Edge edge : solGraph[i]) {
|
||||
System.out.println(i + " <-- weight " + edge.weight + " --> " + edge.to);
|
||||
System.out.println(
|
||||
i + " <-- weight " + edge.weight + " --> " + edge.to
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -74,7 +83,9 @@ public class Kruskal {
|
||||
// captain of i, stores the set with all the connected nodes to i
|
||||
HashSet<Integer>[] connectedGroups = new HashSet[nodes];
|
||||
HashSet<Edge>[] minGraph = new HashSet[nodes];
|
||||
PriorityQueue<Edge> edges = new PriorityQueue<>((Comparator.comparingInt(edge -> edge.weight)));
|
||||
PriorityQueue<Edge> edges = new PriorityQueue<>(
|
||||
(Comparator.comparingInt(edge -> edge.weight))
|
||||
);
|
||||
for (int i = 0; i < nodes; i++) {
|
||||
minGraph[i] = new HashSet<>();
|
||||
connectedGroups[i] = new HashSet<>();
|
||||
@ -87,12 +98,18 @@ public class Kruskal {
|
||||
while (connectedElements != nodes && !edges.isEmpty()) {
|
||||
Edge edge = edges.poll();
|
||||
// This if avoids cycles
|
||||
if (!connectedGroups[captain[edge.from]].contains(edge.to)
|
||||
&& !connectedGroups[captain[edge.to]].contains(edge.from)) {
|
||||
if (
|
||||
!connectedGroups[captain[edge.from]].contains(edge.to) &&
|
||||
!connectedGroups[captain[edge.to]].contains(edge.from)
|
||||
) {
|
||||
// merge sets of the captains of each point connected by the edge
|
||||
connectedGroups[captain[edge.from]].addAll(connectedGroups[captain[edge.to]]);
|
||||
connectedGroups[captain[edge.from]].addAll(
|
||||
connectedGroups[captain[edge.to]]
|
||||
);
|
||||
// update captains of the elements merged
|
||||
connectedGroups[captain[edge.from]].forEach(i -> captain[i] = captain[edge.from]);
|
||||
connectedGroups[captain[edge.from]].forEach(i ->
|
||||
captain[i] = captain[edge.from]
|
||||
);
|
||||
// add Edge to minimal graph
|
||||
addEdge(minGraph, edge.from, edge.to, edge.weight);
|
||||
// count how many elements have been merged
|
||||
|
@ -1,9 +1,9 @@
|
||||
package com.thealgorithms.datastructures.graphs;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Queue;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Queue;
|
||||
|
||||
/**
|
||||
* Implementation of a graph in a matrix form Also known as an adjacency matrix
|
||||
@ -71,7 +71,9 @@ class AdjacencyMatrixGraph {
|
||||
public AdjacencyMatrixGraph(int givenNumberOfVertices) {
|
||||
this.setNumberOfVertices(givenNumberOfVertices);
|
||||
this.setNumberOfEdges(0);
|
||||
this.setAdjacency(new int[givenNumberOfVertices][givenNumberOfVertices]);
|
||||
this.setAdjacency(
|
||||
new int[givenNumberOfVertices][givenNumberOfVertices]
|
||||
);
|
||||
for (int i = 0; i < givenNumberOfVertices; i++) {
|
||||
for (int j = 0; j < givenNumberOfVertices; j++) {
|
||||
this.adjacency()[i][j] = AdjacencyMatrixGraph.EDGE_NONE;
|
||||
@ -101,7 +103,7 @@ class AdjacencyMatrixGraph {
|
||||
* Updates the number of edges in the graph
|
||||
*
|
||||
* @param newNumberOfEdges
|
||||
*
|
||||
*
|
||||
*/
|
||||
private void setNumberOfEdges(int newNumberOfEdges) {
|
||||
this._numberOfEdges = newNumberOfEdges;
|
||||
@ -249,7 +251,11 @@ class AdjacencyMatrixGraph {
|
||||
* has been visited
|
||||
* @param orderList the list to add vertices to as they are visited
|
||||
*/
|
||||
private void depthFirstOrder(int currentVertex, boolean[] visited, List<Integer> orderList) {
|
||||
private void depthFirstOrder(
|
||||
int currentVertex,
|
||||
boolean[] visited,
|
||||
List<Integer> orderList
|
||||
) {
|
||||
// If this vertex has already been visited, do nothing and return
|
||||
if (visited[currentVertex]) {
|
||||
return;
|
||||
@ -262,9 +268,11 @@ class AdjacencyMatrixGraph {
|
||||
|
||||
// Get the adjacency array for this vertex
|
||||
int[] adjacent = _adjacency[currentVertex];
|
||||
for (int i = 0; i < adjacent.length; i++) // If an edge exists between the currentVertex and the vertex
|
||||
// we are considering exploring, recurse on it
|
||||
{
|
||||
for (
|
||||
int i = 0;
|
||||
i < adjacent.length;
|
||||
i++
|
||||
) { // we are considering exploring, recurse on it // If an edge exists between the currentVertex and the vertex
|
||||
if (adjacent[i] == AdjacencyMatrixGraph.EDGE_EXIST) {
|
||||
depthFirstOrder(i, visited, orderList);
|
||||
}
|
||||
@ -310,12 +318,14 @@ class AdjacencyMatrixGraph {
|
||||
orderList.add(currentVertex);
|
||||
visited[currentVertex] = true;
|
||||
|
||||
// Get the adjacency array for the currentVertex and
|
||||
// Get the adjacency array for the currentVertex and
|
||||
// check each node
|
||||
int[] adjacent = _adjacency[currentVertex];
|
||||
for (int vertex = 0; vertex < adjacent.length; vertex++) // If an edge exists between the current vertex and the
|
||||
// vertex we are considering exploring, we add it to the queue
|
||||
{
|
||||
for (
|
||||
int vertex = 0;
|
||||
vertex < adjacent.length;
|
||||
vertex++
|
||||
) { // vertex we are considering exploring, we add it to the queue // If an edge exists between the current vertex and the
|
||||
if (adjacent[vertex] == AdjacencyMatrixGraph.EDGE_EXIST) {
|
||||
queue.add(vertex);
|
||||
}
|
||||
|
@ -5,6 +5,7 @@ package com.thealgorithms.datastructures.graphs;
|
||||
* matrix representation of the graph
|
||||
*/
|
||||
class PrimMST {
|
||||
|
||||
// Number of vertices in the graph
|
||||
|
||||
private static final int V = 5;
|
||||
@ -30,7 +31,9 @@ class PrimMST {
|
||||
void printMST(int parent[], int n, int graph[][]) {
|
||||
System.out.println("Edge Weight");
|
||||
for (int i = 1; i < V; i++) {
|
||||
System.out.println(parent[i] + " - " + i + " " + graph[i][parent[i]]);
|
||||
System.out.println(
|
||||
parent[i] + " - " + i + " " + graph[i][parent[i]]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -69,11 +72,17 @@ class PrimMST {
|
||||
// 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]
|
||||
for (
|
||||
int v = 0;
|
||||
v < V;
|
||||
v++
|
||||
) // Update the key only if graph[u][v] is smaller than key[v] // mstSet[v] is false for vertices not yet included in MST // graph[u][v] is non zero only for adjacent vertices of m
|
||||
{
|
||||
if (graph[u][v] != 0 && mstSet[v] == false && graph[u][v] < key[v]) {
|
||||
if (
|
||||
graph[u][v] != 0 &&
|
||||
mstSet[v] == false &&
|
||||
graph[u][v] < key[v]
|
||||
) {
|
||||
parent[v] = u;
|
||||
key[v] = graph[u][v];
|
||||
}
|
||||
@ -94,9 +103,13 @@ class PrimMST {
|
||||
(3)-------(4)
|
||||
9 */
|
||||
PrimMST t = new PrimMST();
|
||||
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},};
|
||||
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);
|
||||
|
Reference in New Issue
Block a user