将邻接矩阵的代码转换为java中的邻接列表的代码

时间:2013-11-22 02:46:42

标签: java

private int maxVertices;
    private Vertex[] vertices; // array of nodes
    private int[][] edges; // adjacency matrix
    int activeVertices;

    public Graph(int maxSize) {
        maxVertices = maxSize;
        vertices = new Vertex[maxVertices];
        edges = new int[maxVertices][maxVertices]; // allocating adjacency matrix
        activeVertices = 0;
    }

    public void addVertex(Vertex v) {
        if (activeVertices >= maxVertices) {
            System.out.println("Graph full");
            return;
        }
        vertices[activeVertices] = v; // add vertex to list of vertices
        v.graphIndex = activeVertices; // record index of vertex in graph
        activeVertices++;  // increment vertex count
    }

    public void addEdge(Vertex v1, Vertex v2) {
        edges[v1.graphIndex][v2.graphIndex] = 1;
        edges[v2.graphIndex][v1.graphIndex] = 1;
    }

    private void clearVisited() {
        for (int i=0; i<activeVertices; i++) {
            vertices[i].visited=false;
        }

我想使图的这种实现使用邻接矩阵的邻接列表用于存储目的。有人可以告诉我如何利用邻接表来表示这些数据

1 个答案:

答案 0 :(得分:1)

只是为了给你更清晰的画面,

邻接矩阵

adm http://d2o58evtke57tz.cloudfront.net/wp-content/uploads/adjacency_matrix_representation.png

邻接列表

adl http://d2o58evtke57tz.cloudfront.net/wp-content/uploads/adjacency_list_representation.png

代码

public class AdjacencyListGraph implements Graph
{
  /** How many edges this graph has. */
  protected int e;

  /** The index of the last vertex added to this graph. */
  protected int lastAdded;

  /** An array of adjacency lists. */
  protected AdjListInfo[] adj;

  public AdjacencyListGraph(int maxSize)
  {
    lastAdded = -1;
    adj = new AdjListInfo[maxSize];
    e = 0;
  }  

  public Vertex addVertex(Vertex v)
  {
    if (v.getIndex() == Vertex.UNKNOWN_INDEX) {
        lastAdded++;
        v.setIndex(lastAdded);
    } else
        lastAdded = v.getIndex();

    adj[lastAdded] = new AdjListInfo(v);
    return v;
  }  

  public Vertex getVertex(int index)
  {
    return adj[index].thisVertex;
  }

  public void addEdge(Vertex u, Vertex v)
  {
    // Put v on u's list.
    int uIndex = u.getIndex();
    Edge x = new Edge(v, adj[uIndex].head);
    adj[uIndex].head = x;

    // put u on v's list.
    {
        int vIndex = v.getIndex();
        x = new Edge(u, adj[vIndex].head);
        adj[vIndex].head = x;
    }

    e++;
  } 

 /**
 * Inner class for the adjacency list array.
 */
  protected static class AdjListInfo
  {
    /** The vertex whose adjacency list this is. */
    public Vertex thisVertex;

    /** The first edge in this vertex's adjacency list. */
    public Edge head;

    /**
     * Makes an AdjListInfo object for an empty list.
     *
     * @param v The vertex whose adjacency list this is.
     */
    public AdjListInfo(Vertex v)
    {
        thisVertex = v;
        head = null;
    }
  }
}