• 最少转机——图的广度优先遍历


    描述:如图(无向图),5个城市,7调路线,用广度优先求从城市1到达城市5需要转机最少次数。

     1 import java.util.Scanner;
     2 import java.util.LinkedList;
     3 public class One {
     4     public static void main(String args[]){
     5         int m,r,s,e;
     6         Scanner scanner=new Scanner(System.in);
     7         System.out.println("请输入城市的数目、航线数目、起点城市、目的城市:");
     8         m=scanner.nextInt();
     9         r=scanner.nextInt();
    10         s=scanner.nextInt();
    11         e=scanner.nextInt();
    12         int a[][]=new int[m+1][m+1];//用于存储路线
    13         int book[]=new int[m+1];//用于标记已经走过的城市
    14         for(int i=1;i<=m;i++){
    15             for(int j=1;j<=m;j++){
    16                 if(i==j)a[i][j]=0;
    17                 else a[i][j]=9999;//9999为无穷大,表示i、j两点间没有直达航线
    18             }
    19         }
    20         System.out.println("请输入各条直达航线");
    21         for(int k=0;k<r;k++){//设置直达航线
    22             int x=scanner.nextInt();
    23             int y=scanner.nextInt();
    24             a[x][y]=1;
    25             a[y][x]=1;
    26         }
    27         //用于扩展搜索的链表
    28         LinkedList<Note> list=new LinkedList<Note>();
    29         list.add(new Note(s,0));//初始化链表(把起始城市放入链表)
    30         book[s]=1;//标记第一点走过
    31         while(!list.isEmpty()){
    32             for(int i=1;i<=m;i++){
    33                 if(a[list.getFirst().n][i]!=9999&&book[i]==0){
    34                     book[i]=1;
    35                     list.add(new Note(i,list.getFirst().d+1));
    36                 }
    37             }
    38             if(book[e]==1){//到达终点
    39                 break;
    40             }
    41             if(list.getFirst().n!=5){
    42             list.removeFirst();
    43             }
    44         }
    45         System.out.println(list.getLast().d);
    46     }
    47 }
    48 class Note{
    49     int n,d;
    50     Note(int n,int d){
    51         this.n=n;
    52         this.d=d;
    53     }
    54 }
    无向图广度优先

    结果如下:

  • 相关阅读:
    摄像头标定GML Camera Calibration
    joda.money.Money
    aop the less note 1
    good notes
    yingyu biji 1
    flowable note1
    activiti note1
    CET4/6
    Web应用界面好帮手!DevExtreme React和Vue组件全新功能上线
    Web UI开发推荐!Kendo UI for jQuery自定义小部件——处理事件
  • 原文地址:https://www.cnblogs.com/qinmeizhen/p/6817874.html
Copyright © 2020-2023  润新知