我在使用双向链表从文本文件中读取后创建了一个邻接列表,现在使用所述邻接列表我必须从用户那里获取两个输入并使用 Dijkstra 算法我必须找到两个输入之间的最短距离并且我还必须以“1,2,3”格式打印路径,我不知道我会怎么做。所有的边权重也都是 1。 这也是文本文件的格式: 1 2 3 2 1 4 5 3 1 5 4 2 5 5 2 3 4
static void addEdge(LinkedList<LinkedList<Integer> > Adj, int u, int v)
{
// Creating bi-directional vertex
Adj.get(u).add(v);
Adj.get(v).add(u);
}
static void printadjacencylist(LinkedList<LinkedList<Integer> > adj)
{
for (int i = 1; i < adj.size(); ++i)
{
// Printing the head
System.out.print(i + "->");
for (int v : adj.get(i))
{
// Printing the nodes
System.out.print(v + " ");
}
// Now a new line is needed
System.out.println();
}
}
public static void main(String[] args)
{
LinkedList<LinkedList<Integer> > adj = new LinkedList<LinkedList<Integer> >();
ArrayList<Integer>leadValues = new ArrayList<Integer>();
try
{
FileInputStream fileNameStream = new FileInputStream("graph.txt");
Scanner scnr = new Scanner(fileNameStream);
// Creating vertex
int V = 0;
while (scnr.hasNextLine())//loop to read until end of file
{scnr.nextLine(); V++;}
for (int i = 0; i <= V; ++i)
{
adj.add(new LinkedList<Integer>());
}
FileInputStream fileNameStream2 = new FileInputStream("graph.txt");
Scanner scnr2 = new Scanner(fileNameStream2);
while (scnr2.hasNextLine())//loop to read until end of file
{
String input = scnr2.nextLine();
Scanner inputscnr = new Scanner(input);
int lead = Integer.parseInt(inputscnr.next());
if(!leadValues.contains(lead)){leadValues.add(lead);}
while(inputscnr.hasNext())
{
int temp = Integer.parseInt(inputscnr.next());
if(!leadValues.contains(temp))
{
addEdge(adj, lead, temp);
}
}//end while
}//end while
}//end try
catch (FileNotFoundException e)
{
System.out.println("*File does not exist or path was entered incorrectly.*\nPlease try again.");
}//end catch
// Printing adjacency list
printadjacencylist(adj);
}
}