package aaa;
import java.util.*;
public class Main {
static Scanner in = new Scanner(System.in);
static int INF = 99999999;
static boolean[] bool = new boolean[100];
static int[][] matrx = new int[100][100];
static int min = Integer.MAX_VALUE;
static int n,m;
static void dfs(int cur,int dis){
if(dis>min)
return;
//达到终点的话更新最小值
if(cur==n){
if(dis<min)
min=dis;
return;
}
//对于每个点都尝试一遍
for (int i = 1; i <= n; i++) {
//从该点出发有路径并且该顶点未被访问
if(matrx[cur][i]!=INF&&bool[i]==false){
bool[i]=true;
dfs(i,dis+matrx[cur][i]);
bool[i]=false;
}
}
}
public static void main(String[] args) {
Arrays.fill(bool,false);
while(in.hasNext()){
n = in.nextInt();
m = in.nextInt();
for (int i = 1; i <=n; i++) {
for (int j = 1; j <= n; j++) {
if(j==i)
matrx[i][j]=0;
else
matrx[i][j]=INF;
}
}
for (int i = 0; i <m; i++) {
matrx[in.nextInt()][in.nextInt()]=in.nextInt();
}
bool[1]=true;
dfs(1,0);
System.out.println(min);
}
}
}
dfs实现单源点最短路径求解
最新推荐文章于 2021-12-05 13:11:23 发布