简体   繁体   中英

Undirected Graph add/remove Vertex; removeEdge methods

Can anyone help with the following three methods?

addVertex: adds a single vertex

removeEdge: removes an edge between two vertices.

removeVertex: removes a single vertex

Using an adjacency list to represent an undirected graph. The data is in a .txt file (example below):

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

Code:

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();
    }
}
}

Lets start with the easy ones because if you don't nail these down in your head the others are going to be much harder to get :

// 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
}

Make sure you understand how this works. I think what you're missing is how the abstract concept of the Graph is modeled by your use of the Map. When you really understand these methods, you're ready to move on to the others.

Study the Map interface to see what methods are available.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM