有向加权图的邻接表

时间:2010-01-02 00:59:16

标签: java collections adjacency-list

我使用邻接列表来表示有向加权图,并根据this问题提供的示例代码,我创建了以下内容:

import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;

public class _Graph {
    private Map<String, LinkedHashSet<HashMap<String, Integer>>> map = new HashMap<String, LinkedHashSet<HashMap<String, Integer>>>();

    public void addEdge(String node1, String node2, int dist) {
        LinkedHashSet<HashMap<String, Integer>> adjacent = map.get(node1);
        HashMap<String, Integer> innerMap = new HashMap<String, Integer>();
        if(adjacent==null) {
            adjacent = new LinkedHashSet<HashMap<String, Integer>>();                       
            map.put(node1, adjacent);
        }
        innerMap.put(node2, dist);
        adjacent.add(innerMap);
    }

    public boolean isConnected(String node1, String node2) {
        Set<HashMap<String, Integer>> adjacent = map.get(node1);
        if(adjacent==null) {
            return false;
        }
        return adjacent.contains(node2);
    }

    public LinkedList<HashMap<String, Integer>> adjacentNodes(String node) {
        LinkedHashSet<HashMap<String, Integer>> adjacent = map.get(node);
        if(adjacent==null) {
            return new LinkedList<HashMap<String, Integer>>();
        }
        return new LinkedList<HashMap<String, Integer>>(adjacent);
    }

}

我无法使isConnected方法正常工作。我在这里使用错误的数据结构来表示图形(Map<String, LinkedHashSet<HashMap<String, Integer>>>)吗? hashmap将保存连接节点的名称及其距离:

Map<startNode, LinkedHashSet<HashMap<endNode, distanceToEndNode>>>
  1. 基本上我该如何检查一个节点 属于a的邻接列表 给定基节点?我觉得这个问题 减少到正确迭代 超过adjacent Set<HashMap<String, Integer>> 结构,还是我的推理错了?
  2. 在我的第二种方法中 adjacentNodes(String node)我是 返回包含的链表 的地图(在一组结构中) 连接节点及其距离。我怎样才能有效地迭代以查看任何给定节点的所有连接?

1 个答案:

答案 0 :(得分:5)

我认为此处不需要LinkedHashSet,您只需使用Map<String, Map<String, Integer>>来表示图表。

isConnected基本上就是你已有的:

public boolean isConnected(String node1, String node2) {
    Map<String, Integer> adjacent = map.get(node1);
    if(adjacent==null) {
        return false;
    }
    return adjacent.containsKey(node2);
}

adjacentNodes只需要提取源节点哈希集中的条目

public Collection<Map.Entry<String, Integer>> adjacentNodes(String node) {
    Map<String, Integer> adjacent = map.get(node);
    if(adjacent==null) {
        return new ArrayList<Map.Entry<String, Integer>>();
    }
    return adjacent.entrySet();
}
相关问题