【问题标题】:Complexity of this simple algorithm这个简单算法的复杂性
【发布时间】:2016-06-05 21:39:10
【问题描述】:

我做了一个算法来解决一个问题,但我不知道它的复杂性。 该算法验证图的所有顶点是否都是“好”的。 “好”顶点是可以访问图的所有其他顶点的顶点,该路径遵循自己开始的路径。

public static boolean verify(Graph graph)
{
    for(int i=0; i < graph.getVertex().size(); i++)
    {
        // List of vertexes visited 
        ArrayList<Character> accessibleVertex = new ArrayList<Character>();
        getChildren(graph.getVertex().get(i), graph.getVertex().get(i).getName(), accessibleVertex);    

        // If the count of vertex without father equals a count of the list of vertexes visited, his is a "good" vertex
        if((graph.getVertex().size()-1) == accessibleVertex.size())
            return true;
    }

    return false;
}

private static void getChildren(Vertex vertex, char fatherName, ArrayList<Character> accessibleVertex)
{
    // Ignore the 'father'
    if(vertex.getName() != fatherName)
        addIfUnique(vertex.getName(), accessibleVertex);

    for(int i=0; i < vertex.getEdges().size(); i++)
    {
        getChildren(vertex.getEdges().get(i).otherVertex(), fatherName, accessibleVertex);
    }
}

private static void addIfUnique(char name, ArrayList<Character> accessibleVertex)
{
    boolean uniqueVertex = true;

    for(int i=0; i < accessibleVertex.size(); i++)
    {
        if(accessibleVertex.get(i).equals(name))
            uniqueVertex = false;
    }

    if(uniqueVertex)
        accessibleVertex.add(name);
}

Graph tested

感谢和抱歉我的英语。

【问题讨论】:

  • 我的第一印象:O(n^3)
  • 一个名为addIfUnique 的方法采用ArrayList&lt;Character&gt; 建议您应该改用Set&lt;Character&gt;,而只需调用add
  • 我认为如果你的图中存在循环,这段代码可能会无限循环。
  • 是的,代码可以无限循环,但是例如,我有没有边的顶点,所以它是停止的条件

标签: java algorithm code-analysis code-complexity


【解决方案1】:

我认为复杂度是 O(n^2),因为您通过调用来使用嵌套循环:

getChildren(graph.getVertex().get(i), graph.getVertex().get(i).getName(), accessibleVertex);

【讨论】:

  • 那么,verify 中的 for 循环调用 getChildren(),其中包含一个 for 循环 - 这不是嵌套循环?
  • 那么你认为渐近复杂度会是 O(n^2) 吗?
  • 不,我没有就正确的复杂性提出任何要求;我只是在质疑“因为你没有使用嵌套循环”。
  • 那么,所有代码的复杂度都是O(n^2)? addIfUnique 方法不影响复杂度?
  • 方法 addIfUnique 有一个 for 循环,但不会影响,因为如果我们将 for 循环添加到嵌套中,即 O(n) + (n^2),结果将是 O( 2n^2),即渐近,O(n^2)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-10
  • 1970-01-01
相关资源
最近更新 更多