每个城市之间至少有一条航线,找出从一个城市飞到另一个城市需要的最少转机次数
/*
* 由SharpDevelop创建。
* 用户: Administrator
* 日期: 2019/8/28
* 时间: 17:04
*
* 每个城市之间至少有一条航线,找出从一个城市飞到另一个城市需要的最少转机次数。
*
*
* 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
*/
using System;
using System.Collections.Generic;
namespace test5
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("输入城市数量:");
int n = Convert.ToInt32(Console.ReadLine());//城市数
Console.WriteLine("输入航线数量:");
int m = Convert.ToInt32(Console.ReadLine());//航线数
Console.WriteLine("输入起点:");
int s = Convert.ToInt32(Console.ReadLine());//起点
Console.WriteLine("输入终点:");
int e = Convert.ToInt32(Console.ReadLine());//终点
int[,] juzhen = new int[n,n];
int[] bj = new int[n];
for (int i = 0; i < n; i++) {
bj[i] = 0;
for (int j = 0; j < n; j++)
juzhen[i,j] = 0;
}
for (int i = 0; i < m; i++) {
Console.WriteLine("输入第{0}条航线:",i+1);
int ss = Convert.ToInt32(Console.ReadLine());
int es = Convert.ToInt32(Console.ReadLine());
juzhen[ss,es] = 1;
juzhen[es,ss] = 1;
}
int front = 0, fear = 0;
List<City> list=new List<City>();
City city=new City(s,0);
list.Add(city);
fear++;
bj[s] = 1;
while (front < fear)
{
int cityname = list[front].Cityname;
for (int i = 0; i < n; ++i)
{
if (juzhen[cityname,i] == 1 && bj[i] == 0)
{
int number = list[front].Number;
City citys= new City(i, number + 1);
list.Add(citys);
fear++;
bj[i] = 1;
}
if (list[fear - 1].Cityname == e)
{
goto end;
}
}
front++;
}
end:
Console.WriteLine("最少的转机次数为:" + list[fear - 1].Number+"次");
Console.ReadKey();
}
}
class City
{
private int cityname;
public int Cityname {
get { return cityname; }
}
private int number;
public int Number {
get { return number; }
}
public City(int cityname,int number)
{
this.cityname = cityname;
this.number = number;
}
}
}