题解 | #单词缩写#
换乘
http://www.nowcoder.com/practice/15ededab6c85457fa2da50721887a773
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
class Edge{
private int from;
private int to;
private int weight;
public Edge(){
}
public Edge(int from, int to, int weight) {
this.from = from;
this.to = to;
this.weight = weight;
}
public int getFrom() {
return from;
}
public void setFrom(int from) {
this.from = from;
}
public int getTo() {
return to;
}
public void setTo(int to) {
this.to = to;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}}
public class Main {
private static ArrayList<edge> edges = new ArrayList<>();
private static int destination = 0;
private static ArrayList<integer> distanceList = new ArrayList<>();</integer></edge>
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String[] strArr = in.nextLine().split(" ");
destination = Integer.parseInt(strArr[0]);
int n = Integer.parseInt(strArr[1]);
for(int i=0; i<n; i++){
String[] strArr1 = in.nextLine().split(" ");
Edge edge = new Edge(Integer.parseInt(strArr1[0]), Integer.parseInt(strArr1[1]), Integer.parseInt(strArr1[2]));
edges.add(edge);
}
Edge edgestart = new Edge();
int distancestart = 0;
for(int i=0; i<edges.size(); i++){
if(edges.get(i).getFrom()==0){
edgestart = new Edge(edges.get(i).getFrom(), edges.get(i).getTo(), edges.get(i).getWeight());
distancestart = edges.get(i).getWeight();
break;
}
}
getNext(edgestart, distancestart);
if(distanceList.size()==0){
System.out.println("-1");
}
else{
System.out.println(Collections.min(distanceList));
}
}
public static void getNext(Edge edge, int distance){
if( edge.getTo()==destination ){
distanceList.add(Integer.valueOf(distance));
}
else{
for(int i=0; i<edges.size(); i++){
if(edge.getTo() == edges.get(i).getFrom()){
distance += edges.get(i).getWeight();
getNext(edges.get(i), distance);
}
}
}
}}