【问题标题】:Adjacency Lists for graph representation using space O(number of edges)使用空间 O(边数)的图形表示的邻接表
【发布时间】:2015-07-14 16:21:24
【问题描述】:

我正在尝试使用邻接表在 java 中表示一个图(连接非有向无权重)(表示图的空间必须是 O(m),其中 m 是边数),以便使用 BFS 查找一些信息。我从名为 graph.txt 的 txt 中获取有关图形的信息。我不确定我是否使用空间 O(m) 来保存图形,也不确定这是否是保存它以使用 BFS 的好方法。

public class Vertex  {
    boolean visited = false;
    int number;
    ArrayList<Integer> adjList;
    public Vertex(int i) {
        this.number= i;
        adjList = new ArrayList<Integer>(); 
    }
    public void addNeighbor(int i) {
        this.adjList.add(i);
    }
}

【问题讨论】:

    标签: java graph adjacency-list


    【解决方案1】:

    是的,您的表示确实使用了 O(m) 空间。鉴于您的代表,我有两个不同的建议。

    1。 如果你真的想将顶点表示为一个类,那么让它的相邻顶点列表是 List 而不是 List

    2。 由于您的 Vertex 类似乎不包含除顶点的 Integer 值以外的任何信息,为什么不直接使用 Integer 本身呢? 该图可以表示为

    ArrayList<ArrayList<Integer>> graph;
    

    其中 graph[i] 是连接到顶点 i 的顶点列表 这样您就不必从整数 id 到 Vertex 实例中查找匹配项。

    【讨论】:

    • 并不是要把Vertex表示为一个类,我做的第一件事就是把图表示为ArrayList>图;但不确定我是否可以做 BFS 和其他东西,比如用这种表示打印每个级别的顶点。
    【解决方案2】:

    虽然您当然可以使这种表示工作,但您需要一种通过number 访问Vertex 的方法,而无需搜索整个图形。为了使它工作,您需要一个列表或数组 v[]Vertex 对象,这样 v[i].number 总是等于 i

    由于无论如何您都将需要此数组/列表,您不妨使用“空”Vertex 对象预先填充它,并更改表示以使用 Vertex 对象列表而不是 Integer s,从而减少了间接性:

    public class Vertex {
        int number;
        List<Vertex> adjList = new ArrayList<Vertex>();
        public Vertex(int i) {
            this.number= i;
        }
        public void addNeighbor(Vertex v) {
            adjList.add(v);
        }
    }
    

    请注意,将visitedVertex 一起存储可能不是一个好主意,因为visited 是算法状态的一部分,而不是图形表示的一部分。您应该将 visited 布尔变量数组与您的表示分开,并且仅在 BFS 运行期间:

    static void bfs(Vertex[] v, int start) {
        boolean[] visited = new boolean[graph.length];
        Queue<Vertex> q = new Deque<Vertex>();
        q.add(v[start]);
        while (q.peek() != null) {
            Vertex c = q.remove();
            if (visited[c.getNumber()]) {
                continue;
            }
            // Do something with the current vertex c
            ...
            // Mark c visited, and add its neighbors to the queue
            visited[c.getNumber()] = true;
            for (Vector a : c.neighbors()) {
                q.add(a);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-06-10
      • 2013-07-04
      • 2017-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多