Question

In this assignment you will implement the BFS and DFS graph traversal algorithms as a part of the code below (graph.cpp). gra

/* Graph read from file, and represnted as adjacency list.
To implement DFS and BFS on the graph
*/
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <utility>
#include <unordered_map>
#include <set>
#include <queue>

using namespace std;

// Each vertex has an integer id.

typedef vector<vector<pair<int,int>>> adjlist; // Pair: (head vertex, edge weight)

adjlist makeGraph(ifstream& ifs);
void printGraph(const adjlist& alist);
vector<int> BFS(const adjlist& alist, int source); // Return vertices in BFS order
vector<int> DFS(const adjlist& alist, int source); // Return vertices in DFS order
void DFSHelper(const adjlist& alist, vector<int>& dfslist, vector<bool>& visited, int source);
void printQ(queue<int> qcopy);


// DFS - returns list of nodes in DFS order starting from source vertex
vector<int> DFS(const adjlist& alist, int source) {
// Your code here

}

void DFSHelper(const adjlist& alist, vector<int>& dfslist, vector<bool>& visited, int source) {
// Your code here

}

// BFS - returns list of nodes in BFS order starting from source vertex
vector<int> BFS(const adjlist& alist, int source) {
// Your code here

}




// Reads a csv graph from file and returns an adjacency list
adjlist makeGraph(ifstream& ifs) {
int vh, vt, wt;
string line;
unordered_multimap<int, pair<int, int>> elist;
set<int> vlist;

while (getline(ifs, line)) {
stringstream ss(line);
ss >> vt;
if (ss.peek() == ',')
ss.ignore();
ss >> vh;
if (ss.peek() == ',')
ss.ignore();
ss >> wt;

elist.emplace(vt, make_pair(vh, wt));
vlist.insert(vt);
vlist.insert(vh);
}

adjlist res(vlist.size()); // Preallocate vector

for (auto& ele : elist) {
  res.at(ele.first).push_back(make_pair(ele.second.first, ele.second.second));
}
return res;
}

// Prints the adjacency list (only vertices, not edge weights)
void printGraph(const adjlist& alist) {
int i = 0;
for (auto& v : alist) {
cout << i++ << ": ";
for (auto& av : v) {
cout << av.first << " ";
}
cout << endl;
}
}

// Prints queue for debugging
void printQ(queue<int> qcopy) {
while (!qcopy.empty()) {
cout << qcopy.front();
qcopy.pop();
}
cout << endl;
}

int main() {
ifstream ifs("sample_edges.txt");
adjlist alist = makeGraph(ifs);
printGraph(alist);
vector<int> dfslist = DFS(alist, 0);
for (auto& ele : dfslist) // Prints 0 2 4 5 1 3
cout << ele << " ";
cout << endl;

vector<int> bfslist = BFS(alist, 0);
for (auto& ele : bfslist) // Prints 0 2 1 4 3 5
cout << ele << " ";
cout << endl;

}

// sampletxt
//0, 1, 1
//0, 2, 1
//1, 3, 1
//2, 4, 1
//3, 4, 1
//3, 5, 1
//4, 5, 1
//0, 1, 1
//0, 2, 1
//1, 3, 1
//2, 4, 1
//3, 4, 1

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Working code implemented in C++ and appropriate comments provided for better understanding:

Here I am attaching code for these files:

  • graph_test.cpp
  • graph.cpp

Source code for graph_test.cpp:

/* Test for BFS and DFS */
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <utility>
#include <unordered_map>
#include <set>
#include <queue>

using namespace std;

// Each vertex has an integer id.

typedef vector<vector<pair<int,int>>> adjlist; // Pair: (head vertex, edge weight)
adjlist makeGraph(ifstream& ifs);
void printGraph(const adjlist& alist);
vector<int> BFS(const adjlist& alist, int source); // Return vertices in BFS order
vector<int> DFS(const adjlist& alist, int source); // Return vertices in DFS order

int main() {
ifstream ifs("sample_edges.txt");
adjlist alist = makeGraph(ifs);
printGraph(alist);
vector<int> dfslist = DFS(alist, 0);
for (auto& ele : dfslist) // Prints 0 2 4 5 1 3
cout << ele << " ";
cout << endl;
  
vector<int> bfslist = BFS(alist, 0);
for (auto& ele : bfslist) // Prints 0 2 1 4 3 5
cout << ele << " ";
cout << endl;
}

Source code for graph.cpp:

/* Graph read from file, and represnted as adjacency list.
To implement DFS and BFS on the graph
*/
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <utility>
#include <unordered_map>
#include <set>
#include <queue>

using namespace std;

// Each vertex has an integer id.

typedef vector<vector<pair<int,int>>> adjlist; // Pair: (head vertex, edge weight)

adjlist makeGraph(ifstream& ifs);
void printGraph(const adjlist& alist);
vector<int> BFS(const adjlist& alist, int source); // Return vertices in BFS order
vector<int> DFS(const adjlist& alist, int source); // Return vertices in DFS order
void DFSHelper(const adjlist& alist, vector<int>& dfslist, vector<bool>& visited, int source);
void printQ(queue<int> qcopy);


// DFS - returns list of nodes in DFS order starting from source vertex
vector<int> DFS(const adjlist& alist, int source) {
   vector<bool> visited;
   vector<int> dfslist;
   for(auto& x : alist){
       visited.push_back(false);
   }
   DFSHelper(alist, dfslist, visited, source);  
   return dfslist;
}

void DFSHelper(const adjlist& alist, vector<int>& dfslist, vector<bool>& visited, int source) {
   visited[source] = true;
   dfslist.push_back(source);  
int i = 0;
for (auto& v : alist) {
if(i == source){
           for(auto& av : v) {
               if(!visited[av.first]){
                   DFSHelper(alist, dfslist, visited, av.first);
               }
           }
       }
       else{
           i++;
       }   
}
}

// BFS - returns list of nodes in BFS order starting from source vertex
vector<int> BFS(const adjlist& alist, int source) {
   vector<bool> visited;
   vector<int> bfslist;
   queue<int> q;
   int add;
   for(auto& x : alist){
       visited.push_back(false);
   }
  
   visited[source] = true;
   q.push(source);  
  
   while(!q.empty()){
       add = q.front();
       bfslist.push_back(add);
       q.pop();
       int i = 0;
       for (auto& v : alist) {
           if(i == add){
               for(auto& av : v) {
                   if(!visited[av.first]){
                       q.push(av.first);
                       visited[av.first] = true;
                   }
               }
           }
           i++;
       }
   }
   return bfslist;
}


// Reads a csv graph from file and returns an adjacency list
adjlist makeGraph(ifstream& ifs) {
int vh, vt, wt;
string line;
unordered_multimap<int, pair<int, int>> elist;
set<int> vlist;
  
while (getline(ifs, line)) {
stringstream ss(line);
ss >> vt;
if (ss.peek() == ',')
ss.ignore();
ss >> vh;
if (ss.peek() == ',')
ss.ignore();
ss >> wt;

elist.emplace(vt, make_pair(vh, wt));   
vlist.insert(vt);
vlist.insert(vh);
}
  
adjlist res(vlist.size()); // Preallocate vector
  
for (auto& ele : elist) {
res.at(ele.first).push_back(make_pair(ele.second.first, ele.second.second));
}
return res;
}

// Prints the adjacency list (only vertices, not edge weights)
void printGraph(const adjlist& alist) {
int i = 0;
for (auto& v : alist) {
cout << i++ << ": ";
for (auto& av : v) {
cout << av.first << " ";
}
cout << endl;
}
}

// Prints queue for debugging
void printQ(queue<int> qcopy) {
while (!qcopy.empty()) {
cout << qcopy.front();
qcopy.pop();
}
cout << endl;
}

Sample Output Screenshots:

sample_edges.txt 1 0,1,1 2 0,2,1 3 1,3,1 4 2,4,1 5 3,4,1 6 3,5,1 7 4,5,1 8 0,1,1 0,2,1 10 1,3,1 11 2,4,1 12 3,4,1 > clang++-7

Hope it helps, if you like the answer give it a thumbs up. Thank you.

Add a comment
Know the answer?
Add Answer to:
/* Graph read from file, and represnted as adjacency list. To implement DFS and BFS on...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • You will be implementing a Breadth-First Search (BFS) and a Depth-First Search (DFS) algorithm on a...

    You will be implementing a Breadth-First Search (BFS) and a Depth-First Search (DFS) algorithm on a graph stored as an adjacency list. The AdjacencyList class inherits from the Graph class shown below. class Graph { private: vector _distances; vector _previous; public: Graph() { } virtual int vertices() const = 0; virtual int edges() const = 0; virtual int distance(int) const = 0; virtual void bfs(int) const = 0; virtual void dfs(int) const = 0; virtual void display() const = 0;...

  • #include <iostream> #include <queue> using namespace std; class Graph { public: Graph(int n); ~Graph(); void addEdge(int...

    #include <iostream> #include <queue> using namespace std; class Graph { public: Graph(int n); ~Graph(); void addEdge(int src, int tar); void BFTraversal(); void DFTraversal(); void printVertices(); void printEdges(); private: int vertexCount; int edgeCount; bool** adjMat; void BFS(int n, bool marked[]); void DFS(int n, bool marked[]); }; Graph::Graph(int n=0) { vertexCount = n; edgeCount = 0; if(n == 0) adjMat = 0; else { adjMat = new bool* [n]; for(int i=0; i < n; i++) adjMat[i] = new bool [n]; for(int i=0;...

  • ADJACENCY LIST ( use Breadth-First Search algorithm) How to get the total number of paths of...

    ADJACENCY LIST ( use Breadth-First Search algorithm) How to get the total number of paths of fixed length from vector of vector adjacency LIST. REMEMBER: the fixed length has to be the shortest length. So, const std::vector< std::vector<unsigned> > & adjList; and I'm supposed to get the number of paths for a given shortest path from the adjList. What I want: 1. To define the function countingGraphPathWays(const vector< vector > &adjVertex, unsigned source, vector & thPathLen, vector & numOfTheShortestPaths) 2....

  • Hi there. I tried to submit this before, but the copy/paste didn't copy my vectors correctly....

    Hi there. I tried to submit this before, but the copy/paste didn't copy my vectors correctly. Hello there. I am trying to implement the djikstras shortest path algorithm into my code in C++ with a vector of vectors. However, when I test I get an error "Exception thrown at 0x75FFC762 in graphMain.exe: Microsoft C++ exception: std::out_of_range at memory location 0x009CF26C" for line 115 in graph.cpp. Could you help me debug? I am so close! ----------------------------FILE NAME: pch.h--------------------------------------- // pch.cpp: source...

  • C++ (Using Binary Search Trees) other methods will result in downvote Implement the binary search tree...

    C++ (Using Binary Search Trees) other methods will result in downvote Implement the binary search tree methods (bst.cpp) for the binary search tree provided in the header file. Test your implementation with the included test. bst.h bst_test.cpp Note: Your implementation must correspond to declarations in the header file, and pass the test. Do not modify these two. I will compile your code against these. If the compilation fails, you will get down vote. bst.h #ifndef BINARY_SEARCH_TREE_H #define BINARY_SEARCH_TREE_H #include <string>...

  • from collections import defaultdict    # This class represents a directed graph using # adjacency list...

    from collections import defaultdict    # This class represents a directed graph using # adjacency list representation class Graph:        # Constructor     def __init__(self):            # default dictionary to store graph         self.graph = defaultdict(list)        # function to add an edge to graph     def addEdge(self,u,v):         self.graph[u].append(v)        # Function to print a BFS of graph     def BFS(self, s):            # Mark all the vertices as not visited         visited = [False] * (len(self.graph))            # Create a queue for BFS         queue...

  • Introduction In this lab, you are supposed to implement a graph class with the data structure...

    Introduction In this lab, you are supposed to implement a graph class with the data structure implemented before like linked list and queue. graph The class graph contains three member variables: linkedList *adjacentVertices; //an array of linked list. For a vertice i, adjacentVertices[i] stores the linked list that contains all other vertices connected to vertice i. int numVertices; //The number of vertices in the graph. int maxNumVertices; //The maximum number of vertices the graph can hold. Following public methods are...

  • I have a Graph.java which I need to complete four methods in the java file: completeGraph(),...

    I have a Graph.java which I need to complete four methods in the java file: completeGraph(), valence(int vid), DFS(int start), and findPathBFS(int start, int end). I also have a JUnit test file GraphTest.java for you to check your code. Here is Graph.java: import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; import java.util.Stack; /* Generic vertex class */ class Vertex<T> { public T data; public boolean visited; public Vertex() { data = null; visited = false; } public Vertex(T _data) { data =...

  • In C++ write a program that will read three strings from the user, a phrase, a...

    In C++ write a program that will read three strings from the user, a phrase, a letter to replace, and a replacement letter. The program will change the phrase by replacing each occurrence of a letter with a replacement letter. For example, if the phrase is Mississippi and the letter to replace is 's' the new phrase will be "miizzizzippi". in the function, replace the first parameter is a modifiable string, the second parameter is the occurrence of a letter...

  • Please answer in C++ Derive a class called Queue from the linked list described in Assignment...

    Please answer in C++ Derive a class called Queue from the linked list described in Assignment 2 (list of Dates). This means the Queue class will inherit all the properties (data and functions) of the linked list. But, since a queue allows pushing only at the back and popping at the front of the list, you will need to prevent the addition in the front and removal at the back. To do this, you must derive the Queue class in...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT