【发布时间】:2018-09-18 22:14:18
【问题描述】:
我有一个任务。我需要找到两点之间的最短路径。为此,我使用广度优先搜索算法。我创建了类Graph,它具有顶点数量和邻接列表。这是我的代码:
class Graph
{
private int V;
private LinkedList<Integer> adj[]; //Adjacency Lists
// Constructor
Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList();
}
// Function to add an edge into the graph
void addEdge(int v,int w)
{
adj[v].add(w);
}
// prints BFS traversal from a given source s
void BFS(int s)
{
// Mark all the vertices as not visited(By default
// set as false)
boolean visited[] = new boolean[V];
// Create a queue for BFS
LinkedList<Integer> queue = new LinkedList<Integer>();
// Mark the current node as visited and enqueue it
visited[s]=true;
queue.add(s);
while (queue.size() != 0)
{
// Dequeue a vertex from queue and print it
s = queue.poll();
System.out.print(s+" ");
// Get all adjacent vertices of the dequeued vertex s
// If a adjacent has not been visited, then mark it
// visited and enqueue it
Iterator<Integer> i = adj[s].listIterator();
while (i.hasNext())
{
int n = i.next();
if (!visited[n])
{
visited[n] = true;
queue.add(n);
}
}
}
}
// Driver method to
public static void main(String args[])
{
Graph g = new Graph(8);
g.addEdge(0, 5);
g.addEdge(0, 7);
g.addEdge(1, 5);
g.addEdge(1, 4);
g.addEdge(1, 2);
g.addEdge(2, 1);
g.addEdge(2, 4);
g.addEdge(2, 3);
g.addEdge(3, 4);
g.addEdge(3, 2);
g.addEdge(4, 5);
g.addEdge(4, 1);
g.addEdge(4, 2);
g.addEdge(4, 3);
g.addEdge(5, 0);
g.addEdge(5, 1);
g.addEdge(5, 4);
g.addEdge(6, 7);
g.addEdge(7,6);
g.addEdge(7,0);
g.BFS(2);
g.BFS(2);
}
}
但我需要打印从开始索引到结束的最短路径的函数。我该如何组织它。请帮我。
【问题讨论】:
-
不要重新发明轮子,使用JGraphT。
-
感谢您的帮助,但我无法使用库
-
为什么不能使用库?
-
这是一项奥林匹克任务
-
如果是奥林匹克任务,你不应该自己做吗?