(Hacker Rank) Floyd: City of Blinding Lights - Solution
Link to the problem: https://www.hackerrank.com/challenges/floyd-city-of-blinding-lights
As the name of the problem indicates, the solution below used Floyd-Warshall.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static int[][] adjMatrix;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int numNodes = sc.nextInt();
int numConnections = sc.nextInt();
adjMatrix = new int[numNodes+1][numNodes+1];
for (int i = 1; i <= numNodes; i++) {
for (int j = 1; j <= numNodes; j++) {
if (i == j) {
adjMatrix[i][j] = 0;
continue;
}
adjMatrix[i][j] = 100000;
}
}
for (int i = 0; i < numConnections; i++) {
int n1 = sc.nextInt();
int n2 = sc.nextInt();
int c = sc.nextInt();
adjMatrix[n1][n2] = c;
}
// fill the adjacency matrix
for (int i = 1; i <= numNodes; i++) {
for (int j = 1; j <= numNodes; j++) {
for (int k = 1; k <= numNodes; k++) {
adjMatrix[j][k] = Math.min(adjMatrix[j][k], (adjMatrix[j][i]+adjMatrix[i][k]));
}
}
}
int numQueries = sc.nextInt();
for (int i = 0; i < numQueries; i++) {
int n1 = sc.nextInt();
int n2 = sc.nextInt();
if (adjMatrix[n1][n2] == 100000) {
System.out.println("-1");
continue;
}
System.out.println(adjMatrix[n1][n2]);
}
}
}
As the name of the problem indicates, the solution below used Floyd-Warshall.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static int[][] adjMatrix;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int numNodes = sc.nextInt();
int numConnections = sc.nextInt();
adjMatrix = new int[numNodes+1][numNodes+1];
for (int i = 1; i <= numNodes; i++) {
for (int j = 1; j <= numNodes; j++) {
if (i == j) {
adjMatrix[i][j] = 0;
continue;
}
adjMatrix[i][j] = 100000;
}
}
for (int i = 0; i < numConnections; i++) {
int n1 = sc.nextInt();
int n2 = sc.nextInt();
int c = sc.nextInt();
adjMatrix[n1][n2] = c;
}
// fill the adjacency matrix
for (int i = 1; i <= numNodes; i++) {
for (int j = 1; j <= numNodes; j++) {
for (int k = 1; k <= numNodes; k++) {
adjMatrix[j][k] = Math.min(adjMatrix[j][k], (adjMatrix[j][i]+adjMatrix[i][k]));
}
}
}
int numQueries = sc.nextInt();
for (int i = 0; i < numQueries; i++) {
int n1 = sc.nextInt();
int n2 = sc.nextInt();
if (adjMatrix[n1][n2] == 100000) {
System.out.println("-1");
continue;
}
System.out.println(adjMatrix[n1][n2]);
}
}
}
Comments
Post a Comment