BFS的空间复杂性

时间:2016-12-13 06:49:30

标签: algorithm graph-algorithm breadth-first-search space-complexity

以下是BFS实施的代码片段 -

public static void findShortestReach(LinkedList<Integer>[] adjList,int start,int nodes)
{
    int[] level=new int[nodes];     //keeps track of distance of node in terms of number of edges
    Arrays.fill(level,-1);           //-1 signifies unreachable
    level[start-1]=0;               //distance of start from start is 0
    ArrayList<Integer> frontier=new ArrayList<Integer>();
    frontier.add(start);
    int i=1;
    while(!frontier.isEmpty())          //'nodes' times
    {
        ArrayList<Integer> next=new ArrayList<Integer>();
        for(int j:frontier)
        {   

            for(int k:adjList[j-1])
            {   
                //System.out.println(k+"hi");
                if(level[k-1]==-1)
                {
                    level[k-1]=6*i;
                    next.add(k);
                }

            }
        }
        frontier=next;
        i=i+1;
    }
    for(int l=0;l<nodes;l++)
    {    
        if(level[l]!=0)
        {
            System.out.print(level[l]+" ");


        }

    }



}

其中'start'是起始节点,'nodes'是节点数。上面的算法在空间方面是低效的,因为它在while循环中一次又一次地创建ArrayList。我无法在复杂性方面说服自己。

while循环将运行'节点'次,即V次。这些时间中的每一个都将创建ArrayList,并且随着元素被添加到它的大小将增加。在最坏的情况下它将存储的最大元素数量将是V -1。因此空间复杂度下降为V ^ 2。但是,一旦它被填充,它会捕获到arraylist的加倍,因为在while循环的每次迭代期间会发生多次。在这种情况下如何准确判断空间复杂度?

1 个答案:

答案 0 :(得分:1)

如果我理解这个问题,你的推理是正确的。请注意,复制数据结构的一部分不会增加空间复杂性。在您的情况下,会复制邻接列表(最多包含|V|个节点),但这种情况最多会发生O(|V|)次。总的来说,while循环中的复制需要O(|V|^2)时间,这是由整体运行时复杂性决定的,也是O(|V|^2)

相关问题