我想尝试过滤我的输出深度优先搜索。 此代码的输出为 0 1 2 5 6 。我想过滤它,所以我可以制作最短路径的解决方案,完成到6到 0 2 6 有什么方法可以做到吗?
代码是这样的:
public class DFS {
private int V;
private LinkedList<Integer> adj[];
DFS(int v)
{
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList();
}
void addEdge(int v, int w)
{
adj[v].add(w); }
void DFSUtil(int v,boolean visited[])
{
visited[v] = true;
System.out.print(v+ " ");
Iterator<Integer> i = adj[v].listIterator();
while (i.hasNext())
{
int n = i.next();
if (!visited[n])
DFSUtil(n, visited);
if(visited[6] == true)
break;
}
}
void dfs(int v)
{
boolean visited[] = new boolean[V];
DFSUtil(v, visited); }
这是边缘:
g.addEdge(0,1);
g.addEdge(0,2);
g.addEdge(0,3);
g.addEdge(0,4);
g.addEdge(2,5);
g.addEdge(2,6);
g.addEdge(3,7);
g.addEdge(3,8);
g.addEdge(3,4);
g.addEdge(8,9);
g.addEdge(8,3);
g.addEdge(9,8);
g.addEdge(9,10);
g.addEdge(10,9);
g.addEdge(10,4);
g.addEdge(4,0);
g.addEdge(4,3);
g.addEdge(4,6);
g.addEdge(4,10);
public static void main(String args[])
{
// i put addEdge in here
g.dfs(0);}