Undirected Graph添加/删除Vertex; removeEdge方法

时间:2011-12-17 20:56:40

标签: java graph adjacency-list

任何人都可以使用以下三种方法吗?

addVertex:添加一个顶点

removeEdge:删除两个顶点之间的边。

removeVertex:删除单个顶点

使用邻接列表表示无向图。数据位于.txt文件中(以下示例):

1 2 3 4 5 6 7 8 9

1 2

1 4

1 3

2 4

2 5

3 6

4 6

5 7

5 8

6 9

7 9

8 9

代码:

import java.io.*;
import java.util.*;

public class Graph<T> {

private Map<Integer, List<Integer>> adjacencyList;
protected int numVertices;
protected T[] vertices;

// AdjList & parseFile
public Graph(String fileName) throws FileNotFoundException {
    adjacencyList = new HashMap<Integer, List<Integer>>();
    buildGraphFromFile(fileName);

}

// addVertex
public void addVertex(String[] vertexName) {

}

// removeVertex
public void removeVertex(String[] vertexName) {

}

// addEdge
// connects vertexA to vertexB & vice versa
public void addEdge(int vertexA, int vertexB) {
    edge(vertexA, vertexB);
    edge(vertexB, vertexA);
}

// Connect vertexA to VertexB. If VA already exists in AdjList return
// edges-list &
// add VB to it. If not, create new ArrayList & add VB then add all to
// AdjList
private void edge(int vertexA, int vertexB) {
    List<Integer> edges;
    if (adjacencyList.containsKey(vertexA)) {
        edges = adjacencyList.get(vertexA);
        edges.add(vertexB);
    } else {
        edges = new ArrayList<Integer>();
        edges.add(vertexB);
        this.adjacencyList.put(vertexA, edges);
    }
}

// RemoveEdge
public void removeEdge(int vertexA, int vertexB) {

}

// Returns true if the graph is empty; false otherwise
public boolean isEmpty() {
    return adjacencyList.isEmpty();
}

// Returns the size of the graph
public int size() {
    int size = 0;
    Iterator<Integer> vertices = adjacencyList.keySet().iterator();
    while (vertices.hasNext()) {
        size++;

    }
    return size;
}

// Returns true is VA points to VB vice versa.
public boolean isConnected(int vertexA, int vertexB) {
    List<Integer> edges = getEdges(vertexA);
    return edges.contains(vertexB);
}

// Returns all edges of each vertex.
public List<Integer> getEdges(int vertexA) {
    List<Integer> edges = adjacencyList.get(vertexA);
    if (edges == null) {
        throw new RuntimeException(vertexA + " not present in the graph.");
    }
    return edges;
}

// Reads text file. Line one contains all vertices. Following lines contain
// edges
// (one edge per line).
private void buildGraphFromFile(String fileName)
        throws FileNotFoundException {
    try {
        File file = new File("data.txt");
        InputStreamReader streamReader = new InputStreamReader(
                new FileInputStream(file));
        BufferedReader br = new BufferedReader(streamReader);
        String line = br.readLine();

        // vertices
        if (line != null) {
            String[] vertexName = line.split(" ");
            int[] vertex = new int[vertexName.length];
            for (int i = 0; i < vertex.length; ++i) {
                vertex[i] = Integer.parseInt(vertexName[i]);

            }

            // edges
            while ((line = br.readLine()) != null) {
                String[] tokens = line.split(" ");
                int vertexA = Integer.parseInt(tokens[0]);
                int vertexB = Integer.parseInt(tokens[1]);
                addEdge(vertexA, vertexB);

            }
        }
        br.close();

        // catch exceptions & errors
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    } catch (Exception e) {
        System.out.println("Error: " + e);
    }
}

// String representation
public String toString() {
    StringBuilder builder = new StringBuilder();
    Iterator<Integer> vertices = adjacencyList.keySet().iterator();
    while (vertices.hasNext()) {
        Integer vertex = vertices.next();
        List<Integer> edges = adjacencyList.get(vertex);
        builder.append(vertex);
        builder.append(": ");
        builder.append(edges);
        builder.append('\n');
    }
    return builder.toString();
}

// Main method
// Generates initial graph using buildGraphFromFile method
public static void main(String[] args) {
    try {
        Graph initialGraph = new Graph(
                "data.txt");
        System.out.println(initialGraph);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}
}

1 个答案:

答案 0 :(得分:0)

让我们从简单的开始吧,因为如果你不把它们钉在头脑中,那么其他的将会更难获得:

// Just returns true if the graph is empty.
isEmpty() { 
    //HINT: ask the Map<Integer, List<Integer>> adjacencyList if it's size is zero.  There is a convenience method on the Map interface that makes this really simple.
}

//returning the number of vertices
size() {
    //HINT: ask the Map<Integer, List<Integer>> adjacencyList for the number of keys in the map
}

确保您了解其工作原理。我认为你所缺少的是如何通过使用Map来建模图的抽象概念。当你真正理解这些方法时,你就可以继续学习其他方法了。

研究Map界面以了解可用的方法。