Question

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; }; It is up to you how you would like to store the data internally, however, the AdjacencyList class must be stored as an adjacency list as discussed in class. The input file is formatted with the first line being the number of vertices in the graph (labelled 0 - N-1) and the rest of the lines being the edges in a directed graph with the first integer being the source vertex and the second vertex being the sink vertex. 3 0 1 1 2 2 1 2 0 Would be a graph with 3 vertices and the edges { (0->1), (1->2), (2->1), (2->0) }, notice that there is a directed edge both from vertex 1 to 2 and vertex 2 back to 1. It is recommended that you use something similar to the following in the constructor for both lists. // Read in number of vertices. for (unsigned i = 0;i < vertices;++i) { // Initialize vertices } int source, sink; while(/* Can still read edges in */) { // Read in an edge // Add edge to adjacency list (push-back) } The string path(int sink) function will print out the path from the source to the sink vertex passed in. The format for this is {source->next->next->sink} with no whitespace. For example, a path from source 0 to vertex 2 to sink 1 would be output as: {0->2->1} For the dfs() and bfs() functions in your .cpp files, annotate the functions with their run times. In a comment above the function definition specify the runtime and space complexity of your implementation and in comments on each line put the run time of that line of code in your implementation. For helper function calls you don't need to annotate the function definitions. // Overall runtime complexity: O(?) // Overall space complexity: O(?) void foo() { int x = 5; // O(?) int y = bar; // O(?) } int bar() { return 5; // No annotations necessary }

CODE MUST BE DONE WITH THIS HEADER

#ifndef ADJACENCYLIST_H #define ADJACENCYLIST_H #include <vector> #include <string> using namespace std; class Graph { privat

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

BFS() Implementation using Adjacency matrix

Input

You need to give

1. No of vertex in graph

2. No .of edges in graph

3. Start/ source vertex for BFS traversal

Code is

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;

class Graph {

// Number of vertex
int v;

// Number of edges
int e;

// Adjacency matrix
int** adj;

public:
// To create the initial adjacency matrix
Graph(int v, int e);

// Function to insert a new edge
void addEdge(int source, int sink);

// Function to display the BFS traversal
void BFS(int start);
};

// Function to fill the empty adjacency matrix i.e making all elements as 0
Graph::Graph(int v, int e)
{
this->v = v;
this->e = e;
adj = new int*[v];
for (int row = 0; row < v; row++) {
adj[row] = new int[v];
for (int column = 0; column < v; column++) {
adj[row][column] = 0;
}
}
}

// Function to add an edge to the graph
void Graph::addEdge(int source, int sink)
{

// Considering a bidirectional edge
adj[source][sink] = 1;

}

// Function to perform BFS on the graph
void Graph::BFS(int start)
{
// We maintain a visited array to make sure that no vertex is visited more than once
// initially all are false and as soon we visited then we change the status to true
vector<bool> visited(v, false);
vector<int> q;
q.push_back(start);

// Set source as visited change status to true
visited[start] = true;

int vis;
while (!q.empty()) {
vis = q[0];

// Print the current node
cout << vis << " ";
q.erase(q.begin());

// For every adjacent vertex to the current vertex
for (int i = 0; i < v; i++) {
if (adj[vis][i] == 1 && (!visited[i])) {

// Push the adjacent node to the queue
q.push_back(i);

// Set
visited[i] = true;
}
}
}
}

// Driver code
int main()
{
int v , e,v1,v2 ;

// Create the graph
cout<<"Enter the number of vertices in graph ";
cin>>v;
cout<<"enter the number of edges in graph";
cin>>e;
Graph G(v, e);
cout<<"Enter edges by indicating source and sink vertex";
for(int i=0;i<e;i++)
{
cin>>v1>>v2;
G.addEdge(v1, v2);
}
int source;
cout<<"Enter the source vertex of BFS";
cin>>source;
// Perform BC. (USCIS[Juunaliu vei Desktopless programy Uisusingmatrix.exe Enter the number of vertices in graph 3, enter the number of e

BFS
cout<<"BFS Traversal"<<endl;
G.BFS(source);
}

Output ( See output is for the graph given in question if u want to test over any other input you can do it easily)

Time Complexity: O(V+E) where V is number of vertices in the graph and E is number of edges in the graph.

But as we are using adjacency matrix so it become O(V^2)

as to find neighbor we need two loop for searching 1 in matrix

Space Complexity is s O(w) where w is the maximum width of the tree.

Now

DFS() Implementation using Adjacency matrix

Input

You need to give

1. No of vertex in graph

2. No .of edges in graph

3. Start/ source vertex for DFS traversal

Code is

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;

class Graph {

// Indicate Number of vertex
int v;

// Number of edges
int e;

// Adjacency matrix
int** adj;

public:
// To create the initial adjacency matrix
Graph(int v, int e);

// Function to insert a new edge
void addEdge(int source, int sink);

// Function to display the DFS traversal
void DFS(int start, vector<bool>& visited);
};

// Function to fill the empty adjacency matrix
Graph::Graph(int v, int e)
{
// making all positions in matrix as 0
this->v = v;
this->e = e;
adj = new int*[v];
for (int row = 0; row < v; row++) {
adj[row] = new int[v];
for (int column = 0; column < v; column++) {
adj[row][column] = 0;
}
}
}

// Function to add an edge to the graph
void Graph::addEdge(int source, int sink)
{

// Considering a directional edge as directed graph is given so only that position as 1
adj[source][sink] = 1;

}

// Function to perform DFS on the graph
void Graph::DFS(int start, vector<bool>& visited)
{

// Print the current node
cout << start << " ";

// Set current node as visited
visited[start] = true;

// For every node of the graph
for (int i = 0; i < v; i++) {

// If some node is adjacent to the current node
// and it has not already been visited
if (adj[start][i] == 1 && (!visited[i])) {
DFS(i, visited);
}
}
}

// Driver code
int main()
{
int v , e,v1,v2 ;

// Create the graph
cout<<"Enter the number of vertices in graph ";
cin>>v;
cout<<"enter the number of edges in graph";
cin>>e;
Graph G(v, e);
cout<<"Enter edges by indicating source and sink vertex";
for(int i=0;i<e;i++)
{
cin>>v1>>v2;
G.addEdge(v1, v2);
}


// Visited vector to so that
// a vertex is not visited more than once
// Initializing the vector to false as no
// vertex is visited at the beginning
vector<bool> visited(v, false);
int source;
cout<<"Enter the source vertex of DFS";
cin>>source;
// Perform DFS
cout<<"DFS Traversal"<<endl;
G.DFS(source, visited);
}

Output ( See output is for the graph given in question if u want to test over any other input you can do it easily)
- D C:\Users\Sudhanshu Goel\Desktop\ces3 c programing\dfsusingmatrix.exe Enter the number of vertices in graph 3 enter the

Time Complexity: O(V+E) where V is number of vertices in the graph and E is number of edges in the graph.

But as we are using adjacency matrix so it become O(V^2)

as to find neighbor we need two loop for searching 1 in matrix

Space Complexity is O(H) i.e what is max height of the tree   

Add a comment
Know the answer?
Add Answer to:
You will be implementing a Breadth-First Search (BFS) and a Depth-First Search (DFS) algorithm on a...
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
  • /* Graph read from file, and represnted as adjacency list. To implement DFS and BFS on...

    /* 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); //...

  • Show the operation of depth-first search (DFS) on the graph of Figure 1 starting from vertex...

    Show the operation of depth-first search (DFS) on the graph of Figure 1 starting from vertex q. Always process vertices in alphabetical order. Show the discovery and finish times for each vertex, and the classification of each edge. (b) A depth-first forest classifies the edges of a graph into tree, back, forward, and cross edges. A breadth-first search (BFS) tree can also be used to classify the edges reachable from the source of the search into the same four categories....

  • IN C++ Write a BFS path or DFS when it is given a string array of...

    IN C++ Write a BFS path or DFS when it is given a string array of vertices "towns": string towns[]={"Seattle","Lynnwood","Edmonds","Shoreline","Everet","Kenmore","Kirkland"}; and int array of edges: int roads [][2]= {0,1},{0,3}, {1,0},{1,5},   {2,4}, {3,0},{3,5},   {4,2}, {5,1},{5,3},{5,6},   {6,5}; Do not create any graph struct,class or egde struct. You only need to create a BFS or DFS path function that accepts parameters the array of strings, the number of verteces,the array of edges and the nuber of edges. for example you call in main...

  • Help !! I need help with Depth-First Search using an undirected graph. Write a program, IN JAVA, ...

    Help !! I need help with Depth-First Search using an undirected graph. Write a program, IN JAVA, to implement the depth-first search algorithm using the pseudocode given. Write a driver program, which reads input file mediumG.txt as an undirected graph and runs the depth-first search algorithm to find paths to all the other vertices considering 0 as the source. This driver program should display the paths in the following manner: 0 to ‘v’: list of all the vertices traversed to...

  • 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....

  • 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 =...

  • #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;...

  • Please help me with 2 (c), thank you!!! Figure 2: 4 10 Figure 3:1 4 Problems 1. Trace BFS on the following graphs. For...

    Please help me with 2 (c), thank you!!! Figure 2: 4 10 Figure 3:1 4 Problems 1. Trace BFS on the following graphs. For each vertex, record its color, parent, and distance fields, draw the resulting BFS tree, and determine the order in which vertices are added to the Queue. Process adjacency lists in ascending numerical order. a. The graph in figure 1, with 1 as the source. b. The directed graph in figure 2 with 1 as source. 2....

  • please I need it urgent thanks algorithms second picture is the graph 2.3 Graphs and BFS-DFS...

    please I need it urgent thanks algorithms second picture is the graph 2.3 Graphs and BFS-DFS 5 points each I. Draw the adjacency matrix for the graph A on the last page. 2. Show the order in which a breadth first traversal will print out the vertices? Assume that if the algorithm has a choice of which vertex to visit, it visits the vertex with the lower number. 3. Find a topological ordering for the graph B on the last...

  • How would I traverse through this graph? Provide example code, please! class Edge {    int src,...

    How would I traverse through this graph? Provide example code, please! class Edge {    int src, dest;    Edge(int src, int dest)    {        this.src = src;        this.dest = dest;    } }; // class to represent a graph object class Graph {    // A list of lists to represent adjacency list    List<List<Integer>> adj = new ArrayList<>();    // Constructor to construct graph    public Graph(List<Edge> edges)    {        // allocate memory for adjacency list        for (int i = 0; i < edges.size(); i++) {            adj.add(i,...

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