Java 修改DFS方法,使其能够检测图形是否为树

Java 修改DFS方法,使其能够检测图形是否为树,java,graph,tree,depth-first-search,Java,Graph,Tree,Depth First Search,必须更改此DFS方法,以便它可以检查图中是否包含循环。我的问题是编码,因为我在编码方面的经验很少。看起来我的帖子几乎是代码:D public void DFS() { Stack<Integer> stack = new Stack<Integer>(); boolean[] visited = new boolean[N]; for (int i = 0; i < N; i++) { if (!visited[i]) { // find ano

必须更改此DFS方法,以便它可以检查图中是否包含循环。我的问题是编码,因为我在编码方面的经验很少。看起来我的帖子几乎是代码:D

public void DFS()
 {
  Stack<Integer> stack = new Stack<Integer>();
  boolean[] visited = new boolean[N];

  for (int i = 0; i < N; i++) {
  if (!visited[i]) { // find another unvisited vertex

stack.push(i); // and push it into the stack
visited[i] = true; // mark it as visited
System.out.print((i + 1) + " ");

while (!stack.isEmpty()) { // repeat until the stack is empty

 int v = stack.peek(); // get the top vertex in stack

 // trying to find next unvisited neighbor
 boolean hasNeighbor = false;

 for (int j = 0; j < N; j++) {
  if (!visited[j] && connected(v, j)) {
   stack.push(j);
   visited[j] = true;
   System.out.print((j + 1) + " ");

   // so it has an unvisited neighbor vertex
   hasNeighbor = true;

   // found one - don't need to search anymore
   break;
  }
 }

 // if a vertex has no more neighbors
 // we can remove it from the stack
 if (!hasNeighbor)
  stack.pop();
}
 }
  }

System.out.println();
 }
public void DFS()
{
堆栈=新堆栈();
boolean[]访问=新的boolean[N];
对于(int i=0;i
将else语句添加到您的条件中:

if (!visited[i]) { 
我会成功的

所以。。。您的方法应以如下方式结束:

        } else {
          graph = true;
        }
    }
    System.out.println();
}
编辑:您可能需要做一些额外的更改,例如添加另一个布尔数组,以区分您刚刚“访问”的元素,即您位于其左或右子树中的元素和您已经完全访问的节点。 我建议您将现有的布尔数组替换为字节数组:

  • 您访问了一个节点,现在希望访问其左树。无论它是否有一个,在访问它之前,都要将已访问的[node]+

  • 您可以尝试访问其正确的子树。同样的程序

  • 添加一个检查,查看访问的[node]>2。如果是,你肯定有一个图表