使用hashmap构建图形?

时间:2012-11-17 05:42:45

标签: algorithm graph graph-theory depth-first-search breadth-first-search

1)可以使用HashMap表示无向图的邻接列表吗?

HashMap<String,ArrayList<String>>

键将是节点,ArraList将成为边缘。如果对(1)的回答为“是” - 如何在此检查冗余?

例如:

1 -> 2,3,4 2 -> 1,5,6 ... The 1->2 & 2->1 are same.

在这种情况下,如何使用此数据结构执行BFS / DFS?

1 个答案:

答案 0 :(得分:0)

您不必担心冗余问题。 BFS将以正常格式实施。 我很少使用Java,因此它混合了Java和C ++。 而且更正确的HashMap&gt;虽然两者都有效但会是更好的选择。原因:Set具有独特的属性。

Algo:

HashMap<String, ArrayList<String> > graph;
Set<String> visited;
queue<String> currentTraverse; // a data structure which has efficient front removal and back insertion
currentTraverse.push_back(sourcePoint);
visited.insert(sourcePoint);
while(! currentTraverse.empty())
{
    String currentNode = currentTraverse.front();
    currentTraverse.pop_front();
    ArrayList<String> adjacentNodes = graph.find(currentNode)->second;
    for(String node adjacentNodes)
    {
        pair<iterator, bool> isVisited = visited.insert(node);
        if(!isVisited.second) // if not in visited set
            currentTraverse.push_back(node);
    }
}