图(二):无向图的实现

package com.renhui.graph;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * 无向图的实现
 */
public class Graph {

    private final int v; // 记录顶点的数量

    private int e; // 边的数量

    private ConcurrentLinkedQueue[] adj; // 邻接表

    public Graph(int V) {
        this.v = V;  //初始化顶点的数量
        this.e = 0;
        this.adj = new ConcurrentLinkedQueue[v];
        for (int i=0;i<adj.length;i++) {
            adj[i] = new ConcurrentLinkedQueue<Integer>();
        }
    }

    // 获取图中顶点的数量
    public int V() {
        return v;
    }

    // 获取图中边的数量
    public int E() {
        return e;
    }

    // 添加一条边 v-w
    public void addEdge(int v, int w) {
        adj[v].offer(w);
        adj[w].offer(v);
        e++;
    }

    // 获取和顶点v相邻的所有顶点
    public Queue<Integer> adj(int v) {
        return adj[v];
    }

}

 

posted @ 2020-09-06 12:07  灰色飘零  阅读(74)  评论(0)    收藏  举报