表示图的数据类型

有多种数据结构可以表示图,这里探讨的是使用邻接表数组表示图。

邻接表数组:使用一个以顶点为索引的列表数组,每个数组元素为一个Bag对象,对象中存储的是所有与该顶点相邻的顶点。(Bag类似于栈Stack,只能向其中添加元素)。

如下图及其邻接表数组:

由于Graph的实现需要用到Bag,这里先了解一下Bag(背包)的基本知识。

Bag类似于栈都是用于存储数据的,与栈唯一的不同在于Bag只能添加元素。

Bag使用链表存储数据。

Bag的API如下:

Bag的实现代码如下:

import java.util.Iterator;

public class Bag<Item> implements Iterable<Item>{

    private class Node {
        Item item;
        Node next;
    }
    private Node first;
    private int N;

    public boolean isEmpty() {return N==0;}
    public int size() {return N;}

    public void add(Item item) {
        Node temp = new Node();
        temp.item = item;
        temp.next = first;
        first = temp;
    }


    private class ListIterator implements Iterator<Item> {

        private Node current = first;
        @Override
        public boolean hasNext() {
            return current != null;
        }
        @Override
        public Item next() {
            Item temp = current.item;
            current = current.next;
            return temp;
        }
    }

    @Override
    public Iterator<Item> iterator() {
        return new ListIterator();
    }





//    // Bag测试
//    public static void main(String[] args) {
//
//        Bag<Integer> bag = new Bag<>();
//        bag.add(3);
//        bag.add(2);
//        bag.add(3);
//        bag.add(1);
//
//        for (int i:bag)
//            System.out.println(i);
//    }
}

Graph的API如下:

Graph的实现代码如下:

public class Graph {

    private final int V;
    private int E;
    private Bag<Integer>[] adj;
    public Graph(int V) {
        this.V = V;
        this.E = 0;
        adj = (Bag<Integer>[]) new Bag[V];
        for (int v = 0; v<V; v++)
            adj[v] = new Bag<Integer>();
    }

    /** 
     * Return the count of vertices
     */
    public int V() {return V;}

    /**
     *  Return the count of edges
     */
    public int E() {return E;}

    public void addEdge(int v, int w) {
        adj[v].add(w);
        adj[w].add(v);
        E++;
    }

    public Iterable<Integer> adj(int v) {
        return adj[v];
    }

}

猜你喜欢

转载自www.cnblogs.com/deltadeblog/p/9032620.html