最近特别喜欢用递归,今天也遇到了一道题关于图的最短路径的,想想用递归可以做,就编了下,我也不知道这属于数据结构上的那种算法,就照着自己的思路来的,这是无权图的,我想改成有权图也不难无非是把返回路径改成返回权的总和,比较时比较哪个最小
以下是代码
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class 危险系数1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("输入数据");
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
TuNode1[] tuNodes = new TuNode1[n];
int i;
for (i = 0; i < n; i++) {
tuNodes[i] = new TuNode1(i + 1);
}
int x;
int y;
for (i = 0; i < m; i++) {
x = scanner.nextInt();
y = scanner.nextInt();
tuNodes[x - 1].jiedian.add(tuNodes[y - 1]);
tuNodes[y - 1].jiedian.add(tuNodes[x - 1]);
}
System.out.println("输入起点和终点");
int qiDian=scanner.nextInt();
int zhongDian=scanner.nextInt();
List<TuNode1> jiHe = new ArrayList<TuNode1>();
jiHe.add(tuNodes[qiDian-1]);
List<TuNode1> list = search(tuNodes[qiDian-1], tuNodes[zhongDian-1], jiHe);
if (list.size() == 0) {
System.out.println("不存在路径");
} else {
System.out.println(list.size()-1);
}
}
public static List<TuNode1> search(TuNode1 qiDian, TuNode1 zhongDian,
List<TuNode1> jiHe) {
int i;
List<TuNode1> listTemp1;
List<TuNode1> listTemp2 = new ArrayList<TuNode1>();
List<TuNode1> listTemp3 = new ArrayList<TuNode1>();
for (i = 0; i < qiDian.jiedian.size(); i++) {
// 将jiHe中的元素赋给listTemp1
listTemp1 = new ArrayList<TuNode1>(jiHe);
// listTemp2中添加当前循环元素
listTemp2.add(qiDian.jiedian.get(i));
// 对listTemp2取listTemp1的交集
listTemp2.retainAll(listTemp1);
if (qiDian.jiedian.get(i).value == zhongDian.value) {
listTemp1.add(qiDian.jiedian.get(i));
return listTemp1;
} else if (listTemp2.size() == 0) {
listTemp1.add(qiDian.jiedian.get(i));
List<TuNode1> listTemp4 = new ArrayList<TuNode1>(listTemp1);
List<TuNode1> listTemp5 = search(qiDian.jiedian.get(i),
zhongDian, listTemp4);
if (listTemp3.size() != 0) {
if (listTemp5.size() < listTemp3.size()
&& listTemp5.size() != 0) {
listTemp3 = new ArrayList<TuNode1>(listTemp5);
}
} else {
listTemp3 = new ArrayList<TuNode1>(listTemp5);
}
}
listTemp2.clear();
}
return listTemp3;
}
}
class TuNode1 {
int value;
List<TuNode1> jiedian = new ArrayList<TuNode1>();
public TuNode1(int value) {
// TODO Auto-generated constructor stub
this.value = value;
}
}
以下是测试数据
第一行的两个数分别代表节点数和边数
最后一行是求某两个节点间的最短路径
输入数据
7 10
1 2
1 5
1 6
2 6
2 3
2 4
3 4
4 5
4 6
5 6
输入起点和终点
1 3
2
有不好的地方请指出,非常感谢