已知2条地铁线路,其中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 tests; import java.util.Arrays; import java.util.List; public class Main { private int getDistOfTwoStop(List<String>lineNames,String stop1,String stop2,int lineFlag){ // if(lineFlag==1) int dist=0; int stop1Ind=-1; int stop2Ind=-1; int foundNum=0; for(int i=0;i<lineNames.size();i++){ if(lineNames.get(i).equals(stop1)) stop1Ind=i; if(lineNames.get(i).equals(stop2)) stop2Ind=i; if(stop1Ind!=-1&&stop2Ind!=-1){ dist=Math.abs((stop1Ind-stop2Ind))+1; break; } } if(lineFlag==2) return dist; else{ int stopNum=lineNames.size(); if(stopNum-dist+2>dist) return dist; else return stopNum-dist+2; } } private int getDistOfAnyTwoStops(List<String>line1,List<String>line2,String stop1,String stop2){ int dist=0; dist=this.getDistOfTwoStop(line1, stop1, stop2, 1); if(dist>0) return dist; dist=this.getDistOfTwoStop(line2, stop1, stop2, 2); if(dist>0) return dist; String beginStop=""; String endStop=""; if(this.getDistOfTwoStop(line1, stop1, stop1, 1)==1){//stop1 in line1 beginStop=stop1; endStop=stop2; }else{ beginStop=stop2; endStop=stop1; } int distOfStop1ToStopT1=this.getDistOfTwoStop(line1, beginStop, "T1", 1); int distOfStopT1ToStop2=this.getDistOfTwoStop(line2, "T1", endStop, 2); int distOfStop1ToStopT2=this.getDistOfTwoStop(line1, beginStop, "T2", 1); int distOfStopT2ToStop2=this.getDistOfTwoStop(line2, "T2", endStop, 2); if(distOfStop1ToStopT1+distOfStopT1ToStop2<distOfStop1ToStopT2+distOfStopT2ToStop2) return distOfStop1ToStopT1+distOfStopT1ToStop2-1; else return distOfStop1ToStopT2+distOfStopT2ToStop2-1; } public static void main(String[] args) { Main m=new Main(); String []arrayLine1={"A1","A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "T1", "A10", "A11", "A12", "A13", "T2", "A14", "A15", "A16", "A17", "A18"}; String[]arrayLine2={"B1", "B2", "B3", "B4", "B5", "T1", "B6", "B7", "B8", "B9", "B10", "T2", "B11", "B12", "B13", "B14", "B15"}; List<String>line1=Arrays.asList(arrayLine1); List<String>line2=Arrays.asList(arrayLine2); System.out.println(m.getDistOfAnyTwoStops(line1, line2, "B1", "A13")); } }
把最后一句:System.out.println(m.getDistOfAnyTwoStops(line1, line2, "B1", "A13"));中的最后两个参数改改就可输出答案。将数组转化为List貌似冗余了,另外缺少一些注释,不过方法应该行得通,你试试。
A3—A1+1