mirror of
https://github.com/TheAlgorithms/Java.git
synced 2026-03-13 08:40:43 +08:00
@@ -1,83 +1,82 @@
|
||||
/*
|
||||
@author : Mayank K Jha
|
||||
/**
|
||||
* @author Mayank K Jha
|
||||
*/
|
||||
|
||||
*/
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Scanner;
|
||||
import java.util.Stack;
|
||||
|
||||
public class Dijkshtra {
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
public static void main(String[] args) {
|
||||
Scanner in = new Scanner(System.in);
|
||||
|
||||
// n = Number of nodes or vertices
|
||||
int n = in.nextInt();
|
||||
int n = in.nextInt();
|
||||
// m = Number of Edges
|
||||
int m = in.nextInt();
|
||||
int m = in.nextInt();
|
||||
|
||||
// Adjacency Matrix
|
||||
long w[][] = new long [n+1][n+1];
|
||||
long[][] w = new long[n + 1][n + 1];
|
||||
|
||||
//Initializing Matrix with Certain Maximum Value for path b/w any two vertices
|
||||
// Initializing Matrix with Certain Maximum Value for path b/w any two vertices
|
||||
for (long[] row : w) {
|
||||
Arrays.fill(row, 1000000l);
|
||||
Arrays.fill(row, 1000000L);
|
||||
}
|
||||
|
||||
/* From above,we Have assumed that,initially path b/w any two Pair of vertices is Infinite such that Infinite = 1000000l
|
||||
For simplicity , We can also take path Value = Long.MAX_VALUE , but i have taken Max Value = 1000000l */
|
||||
|
||||
// Taking Input as Edge Location b/w a pair of vertices
|
||||
for(int i = 0; i < m; i++) {
|
||||
int x = in.nextInt(),y=in.nextInt();
|
||||
long cmp = in.nextLong();
|
||||
for (int i = 0; i < m; i++) {
|
||||
int x = in.nextInt(), y = in.nextInt();
|
||||
long cmp = in.nextLong();
|
||||
|
||||
//Comparing previous edge value with current value - Cycle Case
|
||||
if(w[x][y] > cmp) {
|
||||
w[x][y] = cmp; w[y][x] = cmp;
|
||||
}
|
||||
// Comparing previous edge value with current value - Cycle Case
|
||||
if (w[x][y] > cmp) {
|
||||
w[x][y] = cmp;
|
||||
w[y][x] = cmp;
|
||||
}
|
||||
}
|
||||
|
||||
// Implementing Dijkshtra's Algorithm
|
||||
Stack<Integer> t = new Stack<Integer>();
|
||||
// Implementing Dijkshtra's Algorithm
|
||||
Stack<Integer> t = new Stack<>();
|
||||
int src = in.nextInt();
|
||||
|
||||
for(int i = 1; i <= n; i++) {
|
||||
if(i != src) {
|
||||
for (int i = 1; i <= n; i++) {
|
||||
if (i != src) {
|
||||
t.push(i);
|
||||
}
|
||||
}
|
||||
|
||||
Stack <Integer> p = new Stack<Integer>();
|
||||
Stack<Integer> p = new Stack<>();
|
||||
p.push(src);
|
||||
w[src][src] = 0;
|
||||
|
||||
while(!t.isEmpty()) {
|
||||
while (!t.isEmpty()) {
|
||||
int min = 989997979;
|
||||
int loc = -1;
|
||||
|
||||
for(int i = 0; i < t.size(); i++) {
|
||||
for (int i = 0; i < t.size(); i++) {
|
||||
w[src][t.elementAt(i)] = Math.min(w[src][t.elementAt(i)], w[src][p.peek()] + w[p.peek()][t.elementAt(i)]);
|
||||
if(w[src][t.elementAt(i)] <= min) {
|
||||
if (w[src][t.elementAt(i)] <= min) {
|
||||
min = (int) w[src][t.elementAt(i)];
|
||||
loc = i;
|
||||
}
|
||||
}
|
||||
p.push(t.elementAt(loc));
|
||||
t.removeElementAt(loc);
|
||||
}
|
||||
}
|
||||
|
||||
// Printing shortest path from the given source src
|
||||
for(int i = 1; i <= n; i++) {
|
||||
if(i != src && w[src][i] != 1000000l) {
|
||||
System.out.print(w[src][i] + " ");
|
||||
for (int i = 1; i <= n; i++) {
|
||||
if (i != src && w[src][i] != 1000000L) {
|
||||
System.out.print(w[src][i] + " ");
|
||||
}
|
||||
// Printing -1 if there is no path b/w given pair of edges
|
||||
else if (i != src) {
|
||||
System.out.print("-1" + " ");
|
||||
}
|
||||
}
|
||||
// Printing -1 if there is no path b/w given pair of edges
|
||||
else if(i != src) {
|
||||
System.out.print("-1" + " ");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,167 +5,174 @@ package Others;
|
||||
* Dijkstra's algorithm,is a graph search algorithm that solves the single-source
|
||||
* shortest path problem for a graph with nonnegative edge path costs, producing
|
||||
* a shortest path tree.
|
||||
*
|
||||
* <p>
|
||||
* NOTE: The inputs to Dijkstra's algorithm are a directed and weighted graph consisting
|
||||
* of 2 or more nodes, generally represented by an adjacency matrix or list, and a start node.
|
||||
*
|
||||
* <p>
|
||||
* Original source of code: https://rosettacode.org/wiki/Dijkstra%27s_algorithm#Java
|
||||
* Also most of the comments are from RosettaCode.
|
||||
*
|
||||
*/
|
||||
//import java.io.*;
|
||||
import java.util.*;
|
||||
public class Dijkstra {
|
||||
private static final Graph.Edge[] GRAPH = {
|
||||
new Graph.Edge("a", "b", 7), //Distance from node "a" to node "b" is 7. In the current Graph there is no way to move the other way (e,g, from "b" to "a"), a new edge would be needed for that
|
||||
new Graph.Edge("a", "c", 9),
|
||||
new Graph.Edge("a", "f", 14),
|
||||
new Graph.Edge("b", "c", 10),
|
||||
new Graph.Edge("b", "d", 15),
|
||||
new Graph.Edge("c", "d", 11),
|
||||
new Graph.Edge("c", "f", 2),
|
||||
new Graph.Edge("d", "e", 6),
|
||||
new Graph.Edge("e", "f", 9),
|
||||
};
|
||||
private static final String START = "a";
|
||||
private static final String END = "e";
|
||||
|
||||
/**
|
||||
* main function
|
||||
* Will run the code with "GRAPH" that was defined above.
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
Graph g = new Graph(GRAPH);
|
||||
g.dijkstra(START);
|
||||
g.printPath(END);
|
||||
//g.printAllPaths();
|
||||
}
|
||||
import java.util.*;
|
||||
|
||||
public class Dijkstra {
|
||||
private static final Graph.Edge[] GRAPH = {
|
||||
// Distance from node "a" to node "b" is 7.
|
||||
// In the current Graph there is no way to move the other way (e,g, from "b" to "a"),
|
||||
// a new edge would be needed for that
|
||||
new Graph.Edge("a", "b", 7),
|
||||
new Graph.Edge("a", "c", 9),
|
||||
new Graph.Edge("a", "f", 14),
|
||||
new Graph.Edge("b", "c", 10),
|
||||
new Graph.Edge("b", "d", 15),
|
||||
new Graph.Edge("c", "d", 11),
|
||||
new Graph.Edge("c", "f", 2),
|
||||
new Graph.Edge("d", "e", 6),
|
||||
new Graph.Edge("e", "f", 9),
|
||||
};
|
||||
private static final String START = "a";
|
||||
private static final String END = "e";
|
||||
|
||||
/**
|
||||
* main function
|
||||
* Will run the code with "GRAPH" that was defined above.
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
Graph g = new Graph(GRAPH);
|
||||
g.dijkstra(START);
|
||||
g.printPath(END);
|
||||
//g.printAllPaths();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class Graph {
|
||||
private final Map<String, Vertex> graph; // mapping of vertex names to Vertex objects, built from a set of Edges
|
||||
|
||||
/** One edge of the graph (only used by Graph constructor) */
|
||||
public static class Edge {
|
||||
public final String v1, v2;
|
||||
public final int dist;
|
||||
public Edge(String v1, String v2, int dist) {
|
||||
this.v1 = v1;
|
||||
this.v2 = v2;
|
||||
this.dist = dist;
|
||||
}
|
||||
}
|
||||
|
||||
/** One vertex of the graph, complete with mappings to neighbouring vertices */
|
||||
public static class Vertex implements Comparable<Vertex> {
|
||||
public final String name;
|
||||
public int dist = Integer.MAX_VALUE; // MAX_VALUE assumed to be infinity
|
||||
public Vertex previous = null;
|
||||
public final Map<Vertex, Integer> neighbours = new HashMap<>();
|
||||
|
||||
public Vertex(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
private void printPath() {
|
||||
if (this == this.previous) {
|
||||
System.out.printf("%s", this.name);
|
||||
}
|
||||
else if (this.previous == null) {
|
||||
System.out.printf("%s(unreached)", this.name);
|
||||
}
|
||||
else {
|
||||
this.previous.printPath();
|
||||
System.out.printf(" -> %s(%d)", this.name, this.dist);
|
||||
}
|
||||
}
|
||||
|
||||
public int compareTo(Vertex other) {
|
||||
if (dist == other.dist)
|
||||
return name.compareTo(other.name);
|
||||
|
||||
return Integer.compare(dist, other.dist);
|
||||
}
|
||||
|
||||
@Override public String toString() {
|
||||
return "(" + name + ", " + dist + ")";
|
||||
}
|
||||
}
|
||||
|
||||
/** Builds a graph from a set of edges */
|
||||
public Graph(Edge[] edges) {
|
||||
graph = new HashMap<>(edges.length);
|
||||
|
||||
//one pass to find all vertices
|
||||
for (Edge e : edges) {
|
||||
if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1));
|
||||
if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2));
|
||||
}
|
||||
|
||||
//another pass to set neighbouring vertices
|
||||
for (Edge e : edges) {
|
||||
graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist);
|
||||
//graph.get(e.v2).neighbours.put(graph.get(e.v1), e.dist); // also do this for an undirected graph
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs dijkstra using a specified source vertex */
|
||||
public void dijkstra(String startName) {
|
||||
if (!graph.containsKey(startName)) {
|
||||
System.err.printf("Graph doesn't contain start vertex \"%s\"\n", startName);
|
||||
return;
|
||||
}
|
||||
final Vertex source = graph.get(startName);
|
||||
NavigableSet<Vertex> q = new TreeSet<>();
|
||||
|
||||
// set-up vertices
|
||||
for (Vertex v : graph.values()) {
|
||||
v.previous = v == source ? source : null;
|
||||
v.dist = v == source ? 0 : Integer.MAX_VALUE;
|
||||
q.add(v);
|
||||
}
|
||||
|
||||
dijkstra(q);
|
||||
}
|
||||
|
||||
/** Implementation of dijkstra's algorithm using a binary heap. */
|
||||
private void dijkstra(final NavigableSet<Vertex> q) {
|
||||
Vertex u, v;
|
||||
while (!q.isEmpty()) {
|
||||
|
||||
u = q.pollFirst(); // vertex with shortest distance (first iteration will return source)
|
||||
if (u.dist == Integer.MAX_VALUE) break; // we can ignore u (and any other remaining vertices) since they are unreachable
|
||||
|
||||
//look at distances to each neighbour
|
||||
for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) {
|
||||
v = a.getKey(); //the neighbour in this iteration
|
||||
|
||||
final int alternateDist = u.dist + a.getValue();
|
||||
if (alternateDist < v.dist) { // shorter path to neighbour found
|
||||
q.remove(v);
|
||||
v.dist = alternateDist;
|
||||
v.previous = u;
|
||||
q.add(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Prints a path from the source to the specified vertex */
|
||||
public void printPath(String endName) {
|
||||
if (!graph.containsKey(endName)) {
|
||||
System.err.printf("Graph doesn't contain end vertex \"%s\"\n", endName);
|
||||
return;
|
||||
}
|
||||
|
||||
graph.get(endName).printPath();
|
||||
System.out.println();
|
||||
}
|
||||
/** Prints the path from the source to every vertex (output order is not guaranteed) */
|
||||
public void printAllPaths() {
|
||||
for (Vertex v : graph.values()) {
|
||||
v.printPath();
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
}
|
||||
// mapping of vertex names to Vertex objects, built from a set of Edges
|
||||
private final Map<String, Vertex> graph;
|
||||
|
||||
/** One edge of the graph (only used by Graph constructor) */
|
||||
public static class Edge {
|
||||
public final String v1, v2;
|
||||
public final int dist;
|
||||
|
||||
public Edge(String v1, String v2, int dist) {
|
||||
this.v1 = v1;
|
||||
this.v2 = v2;
|
||||
this.dist = dist;
|
||||
}
|
||||
}
|
||||
|
||||
/** One vertex of the graph, complete with mappings to neighbouring vertices */
|
||||
public static class Vertex implements Comparable<Vertex> {
|
||||
public final String name;
|
||||
// MAX_VALUE assumed to be infinity
|
||||
public int dist = Integer.MAX_VALUE;
|
||||
public Vertex previous = null;
|
||||
public final Map<Vertex, Integer> neighbours = new HashMap<>();
|
||||
|
||||
public Vertex(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
private void printPath() {
|
||||
if (this == this.previous) {
|
||||
System.out.printf("%s", this.name);
|
||||
} else if (this.previous == null) {
|
||||
System.out.printf("%s(unreached)", this.name);
|
||||
} else {
|
||||
this.previous.printPath();
|
||||
System.out.printf(" -> %s(%d)", this.name, this.dist);
|
||||
}
|
||||
}
|
||||
|
||||
public int compareTo(Vertex other) {
|
||||
if (dist == other.dist)
|
||||
return name.compareTo(other.name);
|
||||
|
||||
return Integer.compare(dist, other.dist);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "(" + name + ", " + dist + ")";
|
||||
}
|
||||
}
|
||||
|
||||
/** Builds a graph from a set of edges */
|
||||
public Graph(Edge[] edges) {
|
||||
graph = new HashMap<>(edges.length);
|
||||
|
||||
// one pass to find all vertices
|
||||
for (Edge e : edges) {
|
||||
if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1));
|
||||
if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2));
|
||||
}
|
||||
|
||||
// another pass to set neighbouring vertices
|
||||
for (Edge e : edges) {
|
||||
graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist);
|
||||
// graph.get(e.v2).neighbours.put(graph.get(e.v1), e.dist); // also do this for an undirected graph
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs dijkstra using a specified source vertex */
|
||||
public void dijkstra(String startName) {
|
||||
if (!graph.containsKey(startName)) {
|
||||
System.err.printf("Graph doesn't contain start vertex \"%s\"\n", startName);
|
||||
return;
|
||||
}
|
||||
final Vertex source = graph.get(startName);
|
||||
NavigableSet<Vertex> q = new TreeSet<>();
|
||||
|
||||
// set-up vertices
|
||||
for (Vertex v : graph.values()) {
|
||||
v.previous = v == source ? source : null;
|
||||
v.dist = v == source ? 0 : Integer.MAX_VALUE;
|
||||
q.add(v);
|
||||
}
|
||||
|
||||
dijkstra(q);
|
||||
}
|
||||
|
||||
/** Implementation of dijkstra's algorithm using a binary heap. */
|
||||
private void dijkstra(final NavigableSet<Vertex> q) {
|
||||
Vertex u, v;
|
||||
while (!q.isEmpty()) {
|
||||
// vertex with shortest distance (first iteration will return source)
|
||||
u = q.pollFirst();
|
||||
if (u.dist == Integer.MAX_VALUE)
|
||||
break; // we can ignore u (and any other remaining vertices) since they are unreachable
|
||||
|
||||
// look at distances to each neighbour
|
||||
for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) {
|
||||
v = a.getKey(); // the neighbour in this iteration
|
||||
|
||||
final int alternateDist = u.dist + a.getValue();
|
||||
if (alternateDist < v.dist) { // shorter path to neighbour found
|
||||
q.remove(v);
|
||||
v.dist = alternateDist;
|
||||
v.previous = u;
|
||||
q.add(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Prints a path from the source to the specified vertex */
|
||||
public void printPath(String endName) {
|
||||
if (!graph.containsKey(endName)) {
|
||||
System.err.printf("Graph doesn't contain end vertex \"%s\"\n", endName);
|
||||
return;
|
||||
}
|
||||
|
||||
graph.get(endName).printPath();
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
/** Prints the path from the source to every vertex (output order is not guaranteed) */
|
||||
public void printAllPaths() {
|
||||
for (Vertex v : graph.values()) {
|
||||
v.printPath();
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user