Question

Creating a simple graph in C++; need solution ASAP. EDIT: Pls comment letting me know what...

Creating a simple graph in C++; need solution ASAP.

EDIT: Pls comment letting me know what other information you need rather than just "..." Thank you.

Here is the assignment:

In this final practice problem, you’ll:
read a set of data representing a directed, unweighted graph build an in-memory graph structure using the data
display the graph using depth-first traversal
display the graph using breadth-first traversal

Input data -

The data consists of records like this: 16 3 15 4 -1

This represents a vertex 16 with neighbors 3, 15, and 4. The -1 is the indicator that no more neighbors for this vertex exist. A vertex with no edges would be represented as follows:

12 -1
Vertex 12 has no edges.

Graph data structure-

The graph data structure is an adjacency list using STL vectors as the underlying structure. It’s based on this struct which represents a vertex:

struct Vertex
int vertexValue;

bool visited;
vector neighbors;

Each vertex has some integer value. There is no relationship between a vertex’s value and its position in the vector; the vertex element 6 might be for the vertex with value 13. Each vertex has some number of neighbors. You don’t know in advance how many vertices will be in the graph, and you don’t know how many neighbors a vertex will have, so it makes sense to have a data structure which is completely flexible in both dimensions. See the “vector of vectors” cheat sheet for examples of how this is coded in C++.

Build and populate the graph-

Main will instantiate the graph. Code a function named buildGraph, which is passed the graph: void buildGraph (vector name)

buildGraph opens the data file. If the open fails, display an error message and exit. For each data record, one vertex is created. You may assume that the data is valid and that each value is separated by spaces. (This means you can use the >> operator). You may also assume that the graph contains at least one vertex.

Before returning, buildGraph should display the graph to make sure that it has been built correctly. See the sample output at the end for an example. It is highly recommended that you code and test buildGraph thoroughly before continuing.

buildGraph builds a data structure that contains vertices, each with a unique value. As stated earlier, there is no relationship between the value of a vertex and its position in the data structure. Therefore, you cannot use the vertex value as the index (subscript) into the graph data structure. Although this assignment uses integer values, the values could as easily be strings, or even other data structures. You will therefore need a table lookup function, which, given a vertex value, returns the index into the vector for the vertex with that value.

Depth-first traversal-

After building the graph, main calls function dft to traverse the graph: void dft (vector name)

dft traverses the graph starting with the first vertex. The first vertex is defined as the first vertex in the graph vector. dft loops through the vertices and calls dftInternal repeatedly with a new vertex each time. dftInternal, in turn, processes all the neighbors for that vertex.

dft is actually a helper function for dftInternal, which is recursive: void dftInternal (vector name, vertex)

When called, dftInternal processes all the neighbors for whichever vertex which has been passed as a parameter. It loops through all its neighbors. A given neighbor might have already been visited; in this case, dftInternal goes on to the next neighbor. Otherwise, it calls itself when it finds a neighbor that has not already been visited.

Refer to the class discussion and the logic to understand how to code dft and dftInternal.

Breadth-first traversal-

The function bft traverses the graph using the breadth-first method: void bft (vector name)

Like dft, bft starts with the first vertex, which is defined as the first vertex in the graph vector. bft is iterative (as opposed to recursive) and uses a queue to keep track of which vertices to process.

bst loops through all the vertices, pushing a vertex onto the queue when it finds one that has not yet been visited. Within that loop, it empties the queue, processing each vertex by pushing any neighbors that have not been visited into the queue. In this manner, all the vertices are pushed onto the queue in breadth-first order. As the queue is emptied, the neighbors for each vertex are examined to determine if they have been visited.
If not, they are added to the queue and the process continues.

Use your queue class from assignment 6 as the queue implementation.

Refer to the class discussion and the logic to understand how to code bft.

Main-

Code a main which instantiates the graph data structure. Main then calls buildGraph, dft, and bft, and exits. The output should resemble something like this (if using the graph from Malik p.696):

Populated graph:
vertex number 0 value 0 neighbors-> 1 5
vertex number 1 value 1 neighbors-> 2 3 5
vertex number 2 value 2 neighbors-> 4
vertex number 3 value 3 neighbors->
vertex number 4 value 4 neighbors-> 3
vertex number 5 value 5 neighbors-> 6
vertex number 6 value 6 neighbors-> 8
vertex number 7 value 7 neighbors-> 8 3
vertex number 8 value 8 neighbors-> 10
vertex number 9 value 9 neighbors-> 4 7 10
vertex number 10 value 10 neighbors->
Depth-first traversal:
0 1 2 4 3 5 6 8 10 7 9
Breadth-first traversal:
0 1 5 2 3 6 4 8 10 7 9
Have a great day!
0 0
Add a comment Improve this question Transcribed image text
Answer #1

BFS:

#include <bits/stdc++.h>
using namespace std;


// initialize adjacency list and visited vectors globally
vector<int> vis;
vector<vector<int> > adj;


// perform bfs procedure
void breadth_first_traversal(int node)
{
   queue<int> q;

   q.push(node);
   vis[node] = true;

   while (!q.empty()) {

       int front = q.front();
       q.pop();

       cout << front << " ";

      
       for (auto i = adj[front].begin(); i != adj[front].end(); i++) {
           if (!vis[*i]) {
               q.push(*i);
               vis[*i] = 1;
           }
       }
   }
}

int main()
{
// take input from user
   int vertices, edges;
   cin >> vertices >> edges;

// intialize visited vertex to 0
   vis.assign(vertices, 0);
   adj.assign(vertices, vector<int>());

// add input edges to adjacency
   int a, b;
   for (int i = 0; i < edges; i++) {
       cin >> a >> b;
  
       adj[a].push_back(b);
       adj[b].push_back(a);
   }

// display the result
   for (int i = 0; i < vertices; i++) {
       if (!vis[i])
           breadth_first_traversal(i);
   }

   return 0;
}

Screenshots:

#include <bits/stdc++.h> using namespace std; // initialize adjacency list and visited vectors globally vector<int> vis; vectvis vis[*i] = 1; int main() // take input from user int vertices, edges; cin >> vertices >> edges; // intialize visited verteUICUULI ILI ULLIUVI JULL return 0;w WONNE0123

DFS:

Code:

#include<bits/stdc++.h>

using namespace std;

int vertices,edges;

vector<int>adj[1001];

// run the dfs algorithm

void dfs(int v, int vis[])

{

// mark the visited vertices as 1

vis[v] = 1;

// display that vertex

cout << v << " ";

// iterate on the neighbours of that vertex and make recursive calls to move depthwise

vector<int>::iterator it;

for (it = adj[v].begin(); it != adj[v].end(); ++it)

if (!vis[*it])

dfs(*it, vis);

}

int main()

{

// take vertices and edges as input from user

cin>>vertices>>edges;

for(int i=0;i<edges;i++){

int u,v;

cin>>u>>v;

adj[u].push_back(v);

adj[v].push_back(u);

}

// intiialize visited array to false

int source;

cin>>source;

int visited[vertices];

for (int i = 0; i < vertices; i++)

visited[i] = 0;

cout << "Depth First Traversal is : \n";

dfs(source,visited);

return 0;

}

Screenshots:

Winclude<bits/stdc++.h> using namespace std; int vertices, edges; vector int>adj[1001]; // run the dfs algorithm void dfs(intvector<int>::iterator it; for (it = adj[v].begin(); it != adj[v].end(); ++it) if (!vis[*it]) dfs(*it, vis); int main() // tak寸ood M N 0 NDepth First Traversal is : 2013

Add a comment
Know the answer?
Add Answer to:
Creating a simple graph in C++; need solution ASAP. EDIT: Pls comment letting me know what...
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
  • Programming Traversal Methods in C++ (depth first & breadth first) Need solution ASAP any help is...

    Programming Traversal Methods in C++ (depth first & breadth first) Need solution ASAP any help is much appreciated. read a set of data representing a directed, unweighted graph build an in-memory graph structure using the data display the graph using depth-first traversal display the graph using breadth-first traversal Input data - The data consists of records like this: 16 3 15 4 -1 This represents a vertex 16 with neighbors 3, 15, and 4. The -1 is the indicator that...

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

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

  • (5 marks) a. The pseudo-code for breadth-first search, modified slightly from Drozdek,1 is as follows: void...

    (5 marks) a. The pseudo-code for breadth-first search, modified slightly from Drozdek,1 is as follows: void breadthFirstSearch (vertex w) for all vertices u num (u) 0 null edges i=1; num (w) i++ enqueue (w) while queue is not empty dequeue ( V= for all vertices u adjacent to v if num(u) is 0 num (u) = i++; enqueue (u) attach edge (vu) to edges; output edges; Now consider the following graph. Give the breadth-first traversal of the graph, starting from...

  • (c) Simulate breadth first search on the graph shown in Fig HW2Q1c. You can assume that...

    (c) Simulate breadth first search on the graph shown in Fig HW2Q1c. You can assume that the starting vertex is 1, and the neighbors of a vertex are examined in increasing numerical order (i.e. if there is a choice between two or more neighbors, we pick the smaller one). You have to show: both the order in which the vertices are visited and the breadth first search tree. No explanations necessary. (d) On the same graph, i.e. the graph in...

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

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

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

  • ***** running late, mere 3 hours left for due time, please help ** #needed in c++...

    ***** running late, mere 3 hours left for due time, please help ** #needed in c++ #inputfile MinPath2.txt 0   SF 1   LA 2   DALLAS 3   CONCORD 4   PHOENIX 5   CHICAGO 6   ST LOUIS 7   BOSTON 8   NY 9   LONDON 10   PARIS 11   TOKYO 12   BANGKOK 13   MEXICO CITY 14   MONTREAL -1   0   1   40 0   2   100 0   4   130 0   8   200 0   9   800 0   10   900 1   2   50 1   3   80 1   4   70 1   8  ...

  • Hello, i need help with this homework: Code provided: public class DirectedWeightedExampleSlide18 { public static void...

    Hello, i need help with this homework: Code provided: public class DirectedWeightedExampleSlide18 { public static void main(String[] args) { int currentVertex, userChoice; Scanner input = new Scanner(System.in); // create graph using your WeightedGraph based on author's Graph WeightedGraph myGraph = new WeightedGraph(4); // add labels myGraph.setLabel(0,"Spot zero"); myGraph.setLabel(1,"Spot one"); myGraph.setLabel(2,"Spot two"); myGraph.setLabel(3,"Spot three"); // Add each edge (this directed Graph has 5 edges, // so we add 5 edges) myGraph.addEdge(0,2,9); myGraph.addEdge(1,0,7); myGraph.addEdge(2,3,12); myGraph.addEdge(3,0,15); myGraph.addEdge(3,1,6); // let's pretend we are on...

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