Ненаправленный график добавить / удалить Vertex;методы removeEdge - PullRequest
0 голосов
/ 18 декабря 2011

Может ли кто-нибудь помочь со следующими тремя методами?

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 голосов
/ 18 декабря 2011

Давайте начнем с легких, потому что, если вы не прибьете их себе в голову, получить другие будет гораздо труднее:

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

Убедитесь, что вы понимаете, как это работает. Я думаю, что вам не хватает того, как абстрактная концепция Графа моделируется вашим использованием Карты. Когда вы действительно поймете эти методы, вы будете готовы перейти к другим.

Изучите интерфейс Карта , чтобы узнать, какие методы доступны.

...