寻飞机最短路径java_深搜寻找最短路径

原创

寻求图中最短路径的方法有很多,最近刚开始学习,先用深搜实现,用邻接矩阵来存储图。

直接上图上代码:

13e5287946ca1cd9f93becf8e7d25893.png

寻求从0~4的最短路径

利用深搜找出所有从0~4的路径,一一比较选择出最小的

import java.util.*;

public class 城市地图 {

static int v; //顶点

static int e; //边

static int matrix[][]; //邻接矩阵

static int book[]; //标记

static int min=99999;

static void dfs(int point,int distinct) {

if(distinct>min) {

return;

}

if(point==v-1) { //目标点是v-1

if(distinct

min=distinct;

return;

}

}

for(int i=0;i

if(matrix[point][i]>0 && matrix[point][i]<99999 && book[i]==0) {

book[i]=1;

dfs(i,distinct+matrix[point][i]);

book[i]=0; //回溯

}

}

return;

}

public static void main(String[] args) {

Scanner reader=new Scanner(System.in);

v=reader.nextInt();

e=reader.nextInt();

matrix=new int[v][v];

book=new int[v];

//矩阵初始化

for(int i=0;i

book[i]=0;

for(int j=0;j

if(i==j) {

matrix[i][j]=0;

}

else {

matrix[i][j]=99999;

}

}

}

//读入边

for(int i=0;i

int first=reader.nextInt();

int second=reader.nextInt();

int dis=reader.nextInt();

matrix[first][second]=dis; //有向图

}

book[0]=1; //起始点是0

dfs(0,0);

System.out.println(min);

}

}

测试数据:

输入:

5 8

0 1 2

0 4 10

1 2 3

1 4 7

2 0 4

2 3 4

3 4 5

4 2 3

输出:9

e37a1d5723e501f4e460ab501c2ba633.png

无向图代码:

import java.util.*;

public class 城市地图_无向 {

static int v;

static int e;

static int matrix[][];

static int book[];

static int min=99999;

static void dfs(int point,int dis) {

if(dis>min) {

return;

}

if(point==v-1) { //到达目的地

if(dis

min=dis;

}

return;

}

for(int i=0;i

if(matrix[point][i]>0 && matrix[point][i]<99999 && book[i]==0) {

book[i]=1;

dfs(i,dis+matrix[point][i]);

book[i]=0; //回溯

}

}

}

public static void main(String[] args) {

Scanner reader=new Scanner(System.in);

v=reader.nextInt();

e=reader.nextInt();

matrix=new int[v][v];

book=new int[v];

//矩阵初始化

for(int i=0;i

book[i]=0;

for(int j=0;j

if(i==j) {

matrix[i][j]=0;

}

else {

matrix[i][j]=99999;

}

}

}

//读入边

for(int i=0;i

int edge_One=reader.nextInt();

int edge_Two=reader.nextInt();

int value=reader.nextInt();

matrix[edge_One][edge_Two]=value; //无向图

matrix[edge_Two][edge_One]=value;

}

book[0]=1;

dfs(0,0);

System.out.println(min);

}

}

测试用例:

输入:

5 8

0 1 2

0 4 10

1 2 3

1 4 7

2 0 4

2 3 4

3 4 5

4 2 3

输出:7

23:40:24

2018-07-23

希望与广大网友互动??

点此进行留言吧!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值