【发布时间】: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);
}
感谢和抱歉我的英语。
【问题讨论】:
-
我的第一印象:O(n^3)
-
一个名为
addIfUnique的方法采用ArrayList<Character>建议您应该改用Set<Character>,而只需调用add。 -
我认为如果你的图中存在循环,这段代码可能会无限循环。
-
是的,代码可以无限循环,但是例如,我有没有边的顶点,所以它是停止的条件
标签: java algorithm code-analysis code-complexity