数据结构实验十的路径问题

本文介绍了在数据结构实验中,如何利用迪杰斯特拉算法求解最短路径问题。虽然该算法能找出最短距离,但无法直接输出路径。作者发现了一个规律,即算法找到的点按顺序排列,排在前面的点离起点越近。通过寻找每个目标点邻接点中顺序最靠前的点,递归回溯,可以得到路径。以起点0到终点9为例,详细阐述了解题思路和过程。
摘要由CSDN通过智能技术生成

数据结构实验十的路径问题

先放代码(关键代码在最后,不要跳过了)
1.这是邻接表的类

package SY10;


public class GraphList{
   
	public static class VertexList{
   
		public String data;
		public EdgeListNode firstEdege;
		public double weight;
		public VertexList(String data,EdgeListNode firstEdege){
   
			this.data=data;
			this.firstEdege=firstEdege;
		}
	}
	public static class EdgeListNode{
   
		public String data;
		public int vertexIndex;
		public EdgeListNode next;
		public double weight;
		public EdgeListNode(int vertexIndex,double weight,EdgeListNode next){
   
			this.vertexIndex=vertexIndex;
			this.weight=weight;
			this.next=next;
		}
		public EdgeListNode(int vertexIndex,String data,double weight,EdgeListNode next){
   
			this.vertexIndex=vertexIndex;
			this.data=data;
			this.weight=weight;
			this.next=next;
		} 
	}
public VertexList[] vertexes;
public int edgeCount;
public GraphList(int vertexCount,int edgeCount){
   
	this.edgeCount=edgeCount;
	this.vertexes=new VertexList[vertexCount];
}
}

2.迪杰斯特拉算法求最短路径

package SY10;

import java.util.Scanner;

import SY10.GraphList.EdgeListNode;
import SY10.GraphList.VertexList;
import SY3.SqStack;

public class SY10_Graph3 {
   
	private static Scanner scanner;
	public static void main(String[] args)throws Exception {
   
		scanner = new Scanner(System.in);
		GraphList graph=createFromConsole1();
		System.out.println("智能省路系统");
		System.out.println("1查询景点信息");
		System.out.println("2查询两个景点路径");
		switch (scanner.nextInt()) {
   
		case 1:
			System.out.println("请输入你想要查询的景点名称:");
			 String point=scanner.next();
			for(int i=0;i<14;i++){
   
				if(point.equals(graph.vertexes[i].data))
					System.out.println(graph.vertexes[i].data);
			}
			break;
		case 2:
			int first=0;
			int end=0;
			System.out.println("请输入你想要查询的两个景点名称:");
			System.out.println("请输入第一个:");
			String point1=scanner.next();
			for(int i=0;i<14;i++){
   
				if(point1.equals(graph.vertexes[i].data))
					first=i;
			}
		    System.out.println("请输入第二个:");
			String point2=scanner.next();
			for(int i=0;i<14;i++){
   
				if(point2.equals(graph.vertexes[i].data))
					end=i;
			}
			dijkstra(graph,first,end);		
			break;
		}
		}
	public static GraphList createFromConsole() {
   
		scanner = new Scanner(System.in);
		System.out.print("请输入顶点数:");
		int vertexCount=scanner.nextInt();
		System.out.print("请输入边数:");
		int edgeCount=scanner.nextInt();
		GraphList graph=new GraphList(vertexCount,edgeCount);
		for(int i=0;i<vertexCount;i++){
   
			graph.vertexes[i]=new VertexList("v"+i,new EdgeListNode
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值