繁体   English   中英

使用广度优先搜索算法检测无向图中的循环

[英]Detect Cycle in an undirected graph using Breadth First Search Algorithm

使用这个算法我得到了错误的答案,但我的测试用例给出了正确的答案。 让我知道我哪里出错了。 在这个算法中,我使用了广度优先搜索(BFS)技术来寻找检测周期。

// Using bfs approach
class Solution{
    public boolean isCycle(int V, ArrayList<ArrayList<Integer>> adj){
        Queue<Integer> q=new LinkedList<>();
        boolean vis[]=new boolean[V];
        int parent[]=new int[V];
        parent[0]=-1;
        q.add(0);
        vis[0]=true;
        while(!q.isEmpty()){
            int cur=q.poll();
            for(int  i:adj.get(cur)){
                // if(vis[i]==true) return true;
                if(!vis[i]){
                    q.add(i);
                    parent[i]=cur;
                    vis[i]=true;
                }
                else if(parent[cur]!=i) return true;
            }
        }
        return false;
    }
}

假设

该方法假设输入无向图是连通的。

请检查对于问题域的所有可能输入,它是否是一个有效的假设。

可能的解决方案

  1. 现有方法适用于单个森林
  2. 向现有方法添加额外的startNodevisited参数
  3. 添加另一个包装器方法,该方法将为每个未访问的节点(森林)调用现有方法。

  boolean hasCycle(final int N, final List<List<Integer>> graph) {
    final boolean[] visited = boolean[N];

    for (int vertex = 0; vertex < N; vertex++) {
      if (!visited[vertex] && hasCycle(N, vertex, visited, graph)) {
        return true;
      }
    }

    return false;
  }

两种方法

  boolean hasCycle(final int N, final int start, final boolean[] visited, final List<List<Integer>> graph) {
    visited[start] = true;

    final int parent[] = new int[N];
    parent[start] = -1;

    final Queue<Integer> q = new LinkedList<>();
    q.add(start);

    while(!q.isEmpty()) {
      final int node = q.poll();

      // assumes for nodes without edges, an empty list will be returned
      for(int adj : graph.get(node)) {
        if (!visited[adj]) {
          q.add(adj);
          parent[adj] = node;
          visited[adj] = true;
        } else if (parent[node] != adj) {
          return true;
        }
      }
    }

    return false;
  }

  boolean hasCycle(final int N, final List<List<Integer>> graph) {
    final boolean[] visited = boolean[N];

    for (int vertex = 0; vertex < N; vertex++) {
      if (!visited[vertex] && hasCycle(N, vertex, visited, graph)) {
        return true;
      }
    }

    return false;
  }

免责声明

这是未经测试和未编译的代码(输入 SO)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM