思路: 同一条线路前面的站可以到后面的站,把一个巴士站点能到的所有的点都用权值为1的边连起来建图。 这样从1到N的边数-1就是换乘次数。 用BFS最短路来写。 登录后复制 import java.util.*; import java.io.*; class Main{ static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static final int N=1000; static int[][] g=new int[N][N]; static int[]dist=new int[N]; static int n,m; public static void bfs(){ Arrays.fill(dist,(int)1e8); Queue<Integer>q=new LinkedList<>(); dist[1]=0; q.add(1); while(!q.isEmpty()){ int t=q.poll(); for(int i=1;i<=n;i++){ if(g[t][i]==1&&t!=i&&dist[i]>dist[t]+1){ q.add(i); dist[i]=dist[t]+1; } } } } public static void main(String[]args)throws IOException{ String[] s=br.readLine().split(" "); m=Integer.parseInt(s[0]); n=Integer.parseInt(s[1]); for(int i=1;i<=m;i++){ s=br.readLine().split(" "); for(int j=0;j<s.length;j++){ for(int k=j+1;k<s.length;k++){ int s1=Integer.parseInt(s[j]); int s2=Integer.parseInt(s[k]); g[s1][s2]=1; } } } bfs(); if(dist[n]>(int)1e8/2)System.out.println("NO"); else System.out.println(dist[n]-1); } } 1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.41.42. 原创作者: u_16969274 转载于: https://blog.51cto.com/u_16969274/11821229