Skip to content

Instantly share code, notes, and snippets.

@feehe21
Created April 8, 2020 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save feehe21/53e140de9f7ecccaec9278ee68f3a630 to your computer and use it in GitHub Desktop.
Save feehe21/53e140de9f7ecccaec9278ee68f3a630 to your computer and use it in GitHub Desktop.
import java.util.*;
public class WeightedGraph
{
int verticies;
List<WGraphEdge>[] a;
public WeightedGraph(int v){
verticies = v;
a = new ArrayList[verticies];
for(int i = 0; i < verticies; i++){
a[i] = new ArrayList<WGraphEdge>();
}
}
public void addEdge(int source, int dest, int length){
WGraphEdge x = new WGraphEdge(length, source, dest);
a[source].add(x);
a[dest].add(x);
}
public void print(){
WGraphEdge e;
for(int i = 0; i < verticies; i++){
System.out.println("");
System.out.print(i + " | ");
for(int j = 0; j < a[i].size(); j++){
e = a[i].get(j);
if(e.source == i){
System.out.print(e.dest);
}else{
System.out.print(e.source);
}
System.out.print(" weight: " + e.length + " | ");
}
}
}
}
public class WGraphEdge
{
int length;
int source;
int dest;
public WGraphEdge(int l, int s, int d){
length = l;
source = s;
dest = d;
}
}
import java.util.*;
public class WGraphRunner
{
WeightedGraph g;
ArrayList<String> list;
public WGraphRunner(){
g = new WeightedGraph(6);
list = new ArrayList<String>();
g.addEdge(0, 1, 4);
g.addEdge(0, 2, 3);
g.addEdge(1, 3, 2);
g.addEdge(1, 2, 5);
g.addEdge(2, 3, 7);
g.addEdge(3, 4, 2);
g.addEdge(4, 0, 4);
g.addEdge(4, 1, 4);
g.addEdge(4, 5, 6);
g.print();
int start = 0;
int end = 3;
int pathLength = findShortest(end,0,start,"");
String path;
for(int i = 1; i < list.size(); i+=2){
if(list.get(i).equals(pathLength+"")){
System.out.print("Path: "+list.get(i-1) + " ");
}
}
System.out.println("Length: " + pathLength);
}
public int findShortest(int finalDest, int length, int focus, String s){
int links = g.a[focus].size();
int smallest = Integer.MAX_VALUE;
int hold;
for(int i = 0; i < links; i++){
if(g.a[focus].get(i).source == finalDest || g.a[focus].get(i).dest == finalDest){
length += g.a[focus].get(i).length;
//System.out.println(s + focus + finalDest);
list.add(s + focus + finalDest);
list.add(length + "");
return length;
}
}
int link;
for(int i = 0; i < g.a[focus].size(); i++){//through connections of focus node
if(g.a[focus].get(i).source == focus){//finds the other end of edge
link = g.a[focus].get(i).dest;
}else{
link = g.a[focus].get(i).source;
}
if(!s.contains(link + "")){
hold = findShortest(finalDest, length + g.a[focus].get(i).length, link, s+focus);
if(hold < smallest){
smallest = hold;
}
}
}
return smallest;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment