2016-06-05 5 views
0

문제를 해결하기위한 알고리즘을 수행했지만 그 복잡성을 알지 못합니다. 알고리즘은 그래프의 모든 정점이 "양호"한지 확인합니다. "좋은"정점은 자신을 시작한 경로를 따라 그래프의 다른 모든 정점에 액세스 할 수있는 정점입니다. 내 영어에 대한이 간단한 알고리즘의 복잡성

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

감사하고 죄송합니다.

+0

내 첫 인상 : O (N^3) – PseudoAj

+0

라는 방법은'addIfUnique'가 복용 'ArrayList '는 대신'Set '을 사용하고'add' 만 호출해야한다고 제안합니다. –

+2

그래프에 사이클이 있으면이 코드가 잠재적으로 루프 할 것입니다. –

답변

2

난 당신이 중첩 루프를 사용하기 때문에 호출하여 복잡도가 O (N^2) 생각 :

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

for 루프를 포함하는'getChildren()'을 호출하는'verify'의 for 루프 - 그건 중첩 된 루프가 아니에요? –

+0

그럼 당신은 점근 적 복잡성이 O (n^2)가 될 것이라고 생각합니까? –

+0

아니요, 저는 정확한 복잡성에 대해 어떠한 주장도하지 않고 있습니다. 나는 "당신이 중첩 된 루프를 사용하지 않았기 때문에"단지 질문하고있을뿐입니다. –