两天地铁路线,A是环形,B是直线型,都是双向的,其中T1,T2是两条地铁的交叉处,求两个地铁站的最少站数,算上起始站和终点站。其中:
地铁线A(环线)经过车站:A1 A2 A3 A4 A5 A6 A7 A8 A9 T1 A10 A11 A12 A13 T2 A14 A15 A16 A17 A18
地铁线B(直线)经过车站:B1 B2 B3 B4 B5 T1 B6 B7 B8 B9 B10 T2 B11 B12 B13 B14 B15
例如输入:A1,A3
例如输出:3
这个代码可以运行,答案不完全正确,有知道哪里错了的同学可以回复跟我说下哈!
package njupt.edu.cn;
import java.util.Scanner;
/*
* 地铁线A(环线)经过车站:A1 A2 A3 A4 A5 A6 A7 A8 A9 T1 A10 A11 A12 A13 T2 A14 A15 A16 A17 A18
* 地铁线B(直线)经过车站:B1 B2 B3 B4 B5 T1 B6 B7 B8 B9 B10 T2 B11 B12 B13 B14 B15
*/
public class Main {
public static void main(String[] args) {
String trainA[] = {"A1","A2","A3","A4","A5","A6","A7","A8","A9","T1","A10","A11","A12","A13","T2","A14","A15","A16","A17","A18"};
String trainB[] = {"B1","B2","B3","B4","B5","T1","B6","B7","B8","B9","B10","T2","B11","B12","B13","B14","B15"};
Scanner s = new Scanner(System.in);
String start;
String end;
int length = 0;
start = s.next();
end = s.next();
if(start.charAt(0)=='T'&&end.charAt(0)=='T'){
length = 6;
}else if((start.charAt(0)==end.charAt(0)&&start.charAt(0)!='T')||(start.charAt(0)=='T'&&end.charAt(0)!='T')||(start.charAt(0)!='T'&&
end.charAt(0)=='T')){
findTheShortestPath(trainA,trainB,start,end);
}else{
int tmp1 = 0,tmp2 = 0;
tmp1 = findTheShortestPath(trainA,trainB,start,"T1")+findTheShortestPath(trainA,trainB,"T1",end);
tmp2 = findTheShortestPath(trainA,trainB,start,"T2")+findTheShortestPath(trainA,trainB,"T2",end);
if(tmp1>tmp2){
length = tmp2;
}else{
length = tmp1;
}
}
System.out.println(length);
s.close();
}
public static int findTheShortestPath(String[] trainA,String[] trainB,String start,String end){
int length = 0;
if((start.charAt(0)=='A'||start.charAt(0)=='T')&&(end.charAt(0)=='A'||end.charAt(0)=='T')){
int indexofstart = 0,indexofend = 0;
for(int i=0;i<trainA.length;i++){
if(trainA[i].equals(start)){
indexofstart = i;
}
if(trainA[i].equals(end)){
indexofend = i;
}
}
if(Math.abs(indexofend-indexofstart)<=11){
length = Math.abs(indexofend-indexofstart);
}else{
length = trainA.length+1-Math.abs(indexofend-indexofstart);
}
}
if((start.charAt(0)=='B'||start.charAt(0)=='T')&&(end.charAt(0)=='B'||end.charAt(0)=='T')){
int indexofstart = 0,indexofend = 0;
for(int i=0;i<trainA.length;i++){
if(trainB[i].equals(start)){
indexofstart = i;
}
if(trainB[i].equals(end)){
indexofend = i;
}
}
length = Math.abs(indexofend-indexofstart);
}
return length;
}
}