【问题标题】:Detect Cycle in an undirected graph using Breadth First Search Algorithm使用广度优先搜索算法检测无向图中的循环
【发布时间】:2021-05-04 14:56:27
【问题描述】:

使用这个算法我得到了错误的答案,但我的测试用例是 给出正确答案。让我知道我哪里出错了。在这个 算法我使用广度优先搜索(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;
    }
}

【问题讨论】:

  • 你的回答有什么“错误”?
  • for (int i : adj.get(cur)) 很可疑。您期望i 成为vis[i] 中的顶点(索引),但实际上您将i 作为边权重。您可以使用经典的for 语句而不是增强的for 语句来更正它。显然还有像if(vis[i]) // break and return这样的其他问题。
  • @AniketSahrawat,您能否详细说明 1.for 声明和 2.if (vis[i])。假设未加权的无向图表示为顶点的邻接列表,则for 循环正确获取相邻顶点。此外,此代码将适用于连接图。不同的森林需要额外调用该方法。

标签: java algorithm graph dsa


【解决方案1】:

假设

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

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

可能的解决方案

  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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多