Pweebs

FindPath.c

Nov 23rd, 2019
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. // Jevin Olano
  2. // jolano
  3. // CSE 101
  4. // November 22, 2019
  5. // FindPath.c
  6.  
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <assert.h>
  10. #include "Graph.h"
  11. #include "List.h"
  12.  
  13. int main (int argc, char* argv[]) {
  14.  
  15. if (argc != 3) {
  16. fprintf(stderr, "Usage %s <input> <output>\n", argv[0]);
  17. exit(1);
  18. }
  19.  
  20. FILE *in = fopen(argv[1], "r");
  21. FILE *out = fopen(argv[2], "w");
  22.  
  23. if (in == NULL) {
  24. printf("Unable to read from file %s\n", argv[1]);
  25. exit(1);
  26. }
  27. if (out == NULL) {
  28. printf("Unable to write to file %s\n", argv[2]);
  29. exit(1);
  30. }
  31.  
  32. int n = 0; // for newGraph(n) later
  33. fscanf(in, "%d", &n);
  34.  
  35. Graph G = newGraph(n); // creates a new Graph object
  36. int tempSource = 0; // temp source vertex for addEdge()
  37. int tempDest = 0; // temp destination vertex for addEdge()
  38. int source = 0; // source for BFS algorithm
  39. int destination = 0; // destination for BFS algorithm
  40.  
  41. while (fgetc(in) != EOF) { // EOF = end of file, recognized by C
  42. fscanf(in, "%d", &tempSource);
  43. fscanf(in, "%d", &tempDest);
  44. if (tempSource == 0 && tempDest == 0) {
  45. break;
  46. }
  47. addEdge(G, tempSource, tempDest);
  48. }
  49. printGraph(out, G);
  50. fprintf(out, "\n");
  51.  
  52. while (fgetc(in) != EOF) { // EOF = end of file, recognized by C
  53.  
  54. fscanf(in, "%d", &source);
  55. fscanf(in, "%d", &destination);
  56. if (source == 0 && destination == 0) {
  57. break;
  58. }
  59. List L = newList();
  60. BFS(G, source);
  61. getPath(L, G, destination);
  62.  
  63. if (getDist(G, destination) != INF) {
  64. fprintf(out, "The distance from %d to %d is %d\n", source, destination, length(L) - 1);
  65. fprintf(out, "A shortest %d-%d path is: ", source, destination);
  66. printList(out, L);
  67. fprintf(out, "\n\n");
  68. } else {
  69. fprintf(out, "The distance from %d to %d is infinity\n", source, destination);
  70. fprintf(out, "No %d-%d path exists\n\n", source, destination);
  71. }
  72. freeList(&L);
  73. }
  74.  
  75. freeGraph(&G);
  76. fclose(in);
  77. fclose(out);
  78. return EXIT_SUCCESS;
  79. }
Add Comment
Please, Sign In to add comment