【问题标题】:graph implementation using adjacency list and HashSets使用邻接表和 HashSet 实现图形
【发布时间】:2013-09-22 07:54:40
【问题描述】:

当我开始将图形实现为邻接列表时,我注意到 检查 v1 是否与 v2 相邻的运行时间为 O(V)

bool isAdjacent(int v1, int v2){    
    for(int i = 0; i < V; ++i){    
        if(this.graph[v1][i] == v2){ return true; }    
    }   
    return false;    
}

循环一直工作到 V(顶点数),所以它是 O(V)

我可以使用 HashSet 代替 ArrayList 或 vector 吗?

原来是ArrayList&lt; ArrayList&lt;Integer&gt; &gt; graph;

Vector&lt; Vector&lt;Integer&gt; &gt; graph;

现在我想知道为什么我们不能创建

ArrayList 图;

这将使 bool isAdjacent(int v1, int v2); O(1) 因为在 HashSet 中搜索的顺序是 O(1)?

如果 hashset 不能使用,因为它比需要的内存要多,那么二叉树呢? ?

ArrayList 图;

在这种情况下,搜索 O(lg V) 比 O(V) 好

谁能帮忙,为什么之前没有创建这个实现??

【问题讨论】:

    标签: graph binary-search-tree hashset


    【解决方案1】:

    是的,您可以(并且应该)为每个顶点使用 HashMap 来存储其邻居列表。

    例如,对于 V1,创建以下 HashMap:

    HashMap<Integer, Boolean> v1Adjacents = new HashMap<Integer, Boolean>();
    

    init期间,你遍历每个顶点的相邻列表并更新它,然后很容易检查V2是否相邻:

    if(v1Adjacents.get(V2) != null){
    ...
    }
    

    【讨论】:

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