This repository acts as a personal archive for my solutions to EdX course *Data Structures and Software Design* from PennX.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
1.3 KiB

  1. import java.io.BufferedReader;
  2. import java.io.FileNotFoundException;
  3. import java.io.FileReader;
  4. import java.io.IOException;
  5. public class GraphBuilder {
  6. public static DirectedGraph buildDirectedGraph(String filename) {
  7. DirectedGraph dg = new DirectedGraph();
  8. try {
  9. buildGraph(dg, filename);
  10. }
  11. catch (Exception e) {
  12. System.out.println("An exception occurred while trying to read " + filename + ": " + e);
  13. return null;
  14. }
  15. return dg;
  16. }
  17. public static UndirectedGraph buildUndirectedGraph(String filename) {
  18. UndirectedGraph ug = new UndirectedGraph();
  19. try {
  20. buildGraph(ug, filename);
  21. }
  22. catch (Exception e) {
  23. System.out.println("An exception occurred while trying to read " + filename + ": " + e);
  24. return null;
  25. }
  26. return ug;
  27. }
  28. protected static void buildGraph(Graph graph, String filename) throws Exception {
  29. try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
  30. String line;
  31. while ((line = br.readLine()) != null) {
  32. String[] edge = line.split(" ");
  33. if (edge.length < 2)
  34. continue;
  35. String source = edge[0];
  36. String destination = edge[1];
  37. Node sourceNode = graph.getNode(source);
  38. Node destinationNode = graph.getNode(destination);
  39. graph.addEdge(
  40. sourceNode, destinationNode);
  41. }
  42. }
  43. }
  44. }