import java.io.*;
import java.util.*;
class Graph
{
private int V; // No. of vertices
private LinkedList<Integer> adj[]; //Adjacency Lists
private LinkedList<Integer> path[];
Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList();
path = new LinkedList[v];
for(int i=0;i<v;++i)
adj[i]=new LinkedList();
}
void addEdge(int v,int w)
{
adj[v].add(w);
}
// prints BFS traversal from a given source s
void BFS(int s,int d)
{
boolean visited[] = new boolean[V];
LinkedList<Integer> queue = new LinkedList<Integer>();
visited[s]=true;
queue.add(s);
path[s].addLast(s);
while (queue.size() != 0)
{
s = queue.poll();
//System.out.print(s+" ");
Iterator<Integer> i = adj[s].listIterator();
while (i.hasNext())
{
int n = i.next();
if (!visited[n])
{
visited[n] = true;
queue.add(n);
path[n]=path[s];
path[n].addLast(n);
}
}
}
System.out.print("Following is the path from source to destination\n");
while(path[d].size()!=0)
{
int xyz=path[d].getFirst();
path[d].poll();
System.out.print(xyz+" ");
}
}
// Driver method to
public static void main(String args[])
{
Graph g = new Graph(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
System.out.println("Following is the desired path\n");
g.BFS(2,3);
}
}
falsch Ich brauche den kürzesten Weg zwischen den Knoten 2 und 3Was in meiner BFS kürzesten Weg Implementierung in Java