package com.xjj.Ah;
import java.util.Scanner;
/*-----深度遍历----最短路径----邻接矩阵---
1.基本模型
* void dfs(int start)
* {
* 标记该点
* 如果所有点访问完返回(return)
* 访问所有点
* for(int i = 1; i <= n; i++)
* {
* 判断(if)是否符合要求;
* 继续下一步 dfs(step+1);
* }
* 返回(return)
* }
* */
public class Ah_5_22dfs {
static int N = 0, M = 0; //点,边 行坐标代表该点,列坐标代表其对其他点
static int[][] a = new int[51][51]; //保存图,点边集
static int[] book = new int[51]; //因为只涉及到点就行,故一维数组
static int Inf = Integer.MAX_VALUE;
static int min = Integer.MAX_VALUE;
int sum = 0;
//深度优先遍历
public void dfs(int start){
//如果当前走过的已经大于已经找到的min,则没必要在遍历下去
if (sum > min)
return;
//如果该节点为目标节点,更新并返回
if (start == 5) {
if ( sum < min)
min = sum;
return;
}
//标记该点已经遍历
book[start] = 1;
//枚举所有节点
for(int i = 1; i <= N; i++){
//如果有路径且未被遍历
if (a[start][i] != Inf && book[i] == 0) {
sum += a[start][i]; //加上当前权值
dfs(i); //深度遍历
sum -= a[start][i]; //减掉上一次遍历权值
book[i] = 0; //将上个节点撤销标记
}
}
//如果所有节点遍历完,则返回上一节点
return;
}
public static void main(String[] args) {
System.out.println("输入图的顶点数及边数:");
Scanner scanner = new Scanner(System.in);
N = scanner.nextInt(); //点
M = scanner.nextInt(); //边
//图初始化
for(int i = 1; i <= N; i++)
for(int j = 1; j <= N; j++)
if (i != j)
a[i][j] = Inf;
for(int i = 1; i <= M; i++){
int x = scanner.nextInt();
int y = scanner.nextInt();
int dis = scanner.nextInt();
a[x][y] = dis;
}
Ah_5_22dfs ah = new Ah_5_22dfs();
ah.dfs(1);
System.out.println("最短路径为: " + min);
}
}
深度遍历----最短路径----邻接矩阵
最新推荐文章于 2023-04-28 20:27:39 发布