Java 如何在有向图上实现深度优先搜索以访问所有顶点
我们如何使用邻接矩阵在有向图上执行深度优先搜索,邻接矩阵从随机顶点开始搜索所有顶点?我试图实现dfs,但它只是探索从起始顶点可以到达的顶点Java 如何在有向图上实现深度优先搜索以访问所有顶点,java,algorithm,graph,depth-first-search,graph-traversal,Java,Algorithm,Graph,Depth First Search,Graph Traversal,我们如何使用邻接矩阵在有向图上执行深度优先搜索,邻接矩阵从随机顶点开始搜索所有顶点?我试图实现dfs,但它只是探索从起始顶点可以到达的顶点 public static void dfs(int [] [] adjMatrix, int startingV,int n) { boolean [] visited = new boolean[n]; Stack<Integer> s = new Stack<Integer>()
public static void dfs(int [] [] adjMatrix, int startingV,int n)
{
boolean [] visited = new boolean[n];
Stack<Integer> s = new Stack<Integer>();
s.push(startingV);
while(!s.isEmpty())
{
int vertex = s.pop();
if(visited[vertex]==false)
{
System.out.print("\n"+(v));
visited[vertex]=true;
}
for ( int i = 0; i < n; i++)
{
if((adjMatrix[vertex][i] == true) && (visited[i] == false))
{
s.push(vertex);
visited[I]=true;
System.out.print(" " + i);
vertex = i;
}
}
}
publicstaticvoiddfs(int[]adjMatrix,int startingV,int n)
{
boolean[]访问=新的boolean[n];
堆栈s=新堆栈();
s、 推动(启动V);
而(!s.isEmpty())
{
int vertex=s.pop();
if(已访问[顶点]==false)
{
系统输出打印(“\n”+(v));
访问[顶点]=真;
}
对于(int i=0;i
}
}
您的代码有两个问题,其中一个是执行
intvertex=s.pop()
和随后的s.push(顶点)代码>具有相同的顶点。后者可能是s.push(i)代码>取而代之
实现DF遍历最简单的方法就是使用递归。然后代码衰减为
function dfs(v) {
if v not visited before {
mark v as visited;
for every adjacent vertex a of v do {
dfs(a);
}
do something with v; // this is *after* all descendants have been visited.
}
}
当然,每个递归实现都可以使用堆栈和迭代来等效地实现,但在您的情况下,这会有点复杂,因为您不仅需要在堆栈上存储当前顶点,还需要在其子体上存储迭代状态(在您的情况下,循环变量i
).在您的情况下,可以选择在顶点上简单地迭代,因为它们由连续整数表示(表示从1到n的i
)。可能不存在一个所有其他顶点都可以到达的顶点。@m.raynal是的,在这种情况下它可以工作,但是如果你选择一个随机的起始顶点呢?那么你无法知道当你开始遍历时会发生什么。它可能会遍历图中的所有顶点,也可能只遍历起始顶点或任意数量的顶点。因此,如果你需要在一个有向图中的所有顶点上迭代,那么图遍历不是一个选项,你需要一个顶点数组或类似的东西。从任何顶点访问所有顶点的唯一情况是如果你的图是强连接的。“深度优先”和“遍历”只适用于遍历边。如果某个节点没有边,则无法遍历该节点。因此,不清楚你到底想要实现什么。