
#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; i < n; i++)
for(int j=0; j < n; j++)
adjMat[i][j] = 0;
}
}
Graph::~Graph() {
for(int i=0; i < vertexCount; i++)
delete [] adjMat[i];
delete [] adjMat;
}
void Graph::addEdge(int src, int tar) {
if(src < 0 || tar < 0 || src > vertexCount-1 || tar > vertexCount-1)
cout << "Invalid vertex index! No edge has been added." << endl;
else if(src == tar)
cout << "No self loop! No edge has been added." << endl;
else if (adjMat[src][tar] == 1)
cout << "This edge already exists. No edge has been added." << endl;
else {
adjMat[src][tar] = 1;
edgeCount++;
}
}
void Graph::BFTraversal() {
// TO DO
// You are expected to call BFS() in this function,
// potentially multiple times in loops.
}
void Graph::BFS(int n, bool marked[]) {
// TO DO
// You are expected to use a queue<int> from C++ STL.
// This function is not recursive, and you are expected to use a while loop.
}
void Graph::DFTraversal() {
// TO DO
// You are expected to call DFS() in this function,
// potentially multiple times in loops.
}
void Graph::DFS(int n, bool marked[]) {
// TO DO
// You are asked to implement this function using recursion.
// However, a for loop is expected --- the recursive calls are within the loop.
}
void Graph::printVertices() {
cout << "This directed graph has " << vertexCount << " vertex (vertices), ";
cout << "indexed from 0 to " << vertexCount-1 << endl;
}
void Graph::printEdges() {
cout << "This directed graph has " << edgeCount << " edge(s):" << endl;
for(int i=0; i < vertexCount; i++)
for(int j=0; j < vertexCount; j++)
if(adjMat[i][j])
cout << "(" << i << "," << j << ")" << endl;
}
int main() {
cout << "Constructing a directed graph..." << endl;
cout << "Please enter the number of vertices in this graph: ";
int n = 0;
cin >> n;
Graph G(n);
while(1) {
cout << "Adding an directed edge..." << endl;
cout << "Trying to add an edge (-1,-1) indicates the end of adding edges and prints outputs." << endl;
cout << "Please enter the vertex index of the source of the edge to be added: ";
int a;
cin >> a;
cout << "Please enter the vertex index of the target of the edge to be added: ";
int b;
cin >> b;
if( a == -1 && b == -1)
break;
else
G.addEdge(a,b);
}
cout << "A directed graph has been constructed:" << endl;
G.printVertices();
G.printEdges();
cout << "Breadth-First Traversal: ";
G.BFTraversal();
cout << "Depth-First Traversal: ";
G.DFTraversal();
return 0;
}
#include <iostream>
#include <list>
#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; i < n; i++)
for(int j=0; j < n; j++)
adjMat[i][j] = 0;
}
}
Graph::~Graph() {
for(int i=0; i < vertexCount; i++)
delete [] adjMat[i];
delete [] adjMat;
}
void Graph::addEdge(int src, int tar) {
if(src < 0 || tar < 0 || src > vertexCount-1 || tar > vertexCount-1)
cout << "Invalid vertex index! No edge has been added." << endl;
else if(src == tar)
cout << "No self loop! No edge has been added." << endl;
else if (adjMat[src][tar] == 1)
cout << "This edge already exists. No edge has been added." << endl;
else {
adjMat[src][tar] = 1;
edgeCount++;
}
}
void Graph::BFTraversal() {
// TO DO
// You are expected to call BFS() in this function,
// potentially multiple times in loops.
bool *marked = new bool[vertexCount]; // array that mark the visited status of node
for(int i = 0; i < vertexCount; i++)
marked[i] = false; // initialize all elements of maeked array to false initially
// calling BFS on each untraversed node, basically this is useful when we have several components in graph that are not connected with each other
for(int j=0;j<vertexCount;j++)
{
if (marked[j]== false)
{
cout<<" \nTraversing from source : " <<j<<endl; // printing the source node
BFS(j,marked); // calling DFS on untraversed node
}
}
}
void Graph::BFS(int n, bool marked[]) {
// TO DO
// You are expected to use a queue<int> from C++ STL.
// This function is not recursive, and you are expected to use a while loop.
queue<int> queue;
queue.push(n); // pushing the element in queue
marked[n] = true; // mark the visisted element
while (!queue.empty()) {
n = queue.front();
queue.pop();
cout << n << " ";
// Enqueue all adjacent of n and mark them visited
for (int i=n; i<vertexCount ;i++)
{
if (!marked[i] && adjMat[n][i]==1)
{
queue.push(i);
marked[i] = true;
}
}
}
}
void Graph::DFTraversal() {
// TO DO
// You are expected to call DFS() in this function,
// potentially multiple times in loops.
bool *marked = new bool[vertexCount]; // array that mark the visited status of node
for(int i = 0; i < vertexCount; i++)
marked[i] = false; // initialize all elements of maeked array to false initially
// calling DFS on each untraversed node, basically this is useful when we have several components in graph that are not connected with each other
for(int j=0;j<vertexCount;j++)
{
if (marked[j]== false)
{
cout<<" \nTraversing from source : " <<j<<endl; // printing the source node
DFS(j,marked); // calling DFS on untraversed node
}
}
}
void Graph::DFS(int n, bool marked[]) {
// TO DO
// You are asked to implement this function using recursion.
// However, a for loop is expected --- the recursive calls are within the loop.
cout << n << " "; // printing the node
marked[n] = true; // making visited node true
for (int i=n; i<vertexCount ;i++)
{
if (!marked[i] && adjMat[n][i]==1)
{
DFS(i,marked); // calling DFS again for unvisited node
}
}
}
void Graph::printVertices() {
cout << "This directed graph has " << vertexCount << " vertex (vertices), ";
cout << "indexed from 0 to " << vertexCount-1 << endl;
}
void Graph::printEdges() {
cout << "This directed graph has " << edgeCount << " edge(s):" << endl;
for(int i=0; i < vertexCount; i++)
for(int j=0; j < vertexCount; j++)
if(adjMat[i][j])
cout << "(" << i << "," << j << ")" << endl;
}
int main() {
cout << "Constructing a directed graph..." << endl;
cout << "Please enter the number of vertices in this graph: ";
int n = 0;
cin >> n;
Graph G(n);
while(1) {
cout << "Adding an directed edge..." << endl;
cout << "Trying to add an edge (-1,-1) indicates the end of adding edges and prints outputs." << endl;
cout << "Please enter the vertex index of the source of the edge to be added: ";
int a;
cin >> a;
cout << "Please enter the vertex index of the target of the edge to be added: ";
int b;
cin >> b;
if( a == -1 && b == -1)
break;
else
G.addEdge(a,b);
}
cout << "A directed graph has been constructed:" << endl;
G.printVertices();
G.printEdges();
cout << "Breadth-First Traversal: ";
G.BFTraversal();
cout << "\nDepth-First Traversal: ";
G.DFTraversal();
return 0;
}
------------------------------------------------------------------------------------------
screenshot of output (example containing a single connected
components)
screenshot of output (example containing a two connected components)

-----------------------------------------------------------------------------------------------------------------------------------------------------------
Please give me a thumbs up when my solution meets your requirement. It motivates us!!
#include <iostream> #include <queue> using namespace std; class Graph { public: Graph(int n); ~Graph(); void addEdge(int...
/* 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); //...
#include <iostream> #include <stack> #include <queue> using namespace std; void printFromStack(string expr){ stack<char> myStack; for(int i=0; i<expr.length(); i++){ //Insert code here to push each character onto the stack } cout << "My stack is popped in this order" << endl; while(!myStack.empty()){ //Insert code here to cout the top of the stack one by one //Pop each one after it’s printed out } cout << endl; } void printFromQueue(string expr){ queue<char> myQueue; //Insert code here to push each character onto the...
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...
#include <iostream> #include <fstream> using namespace std; //constants const int CAP = 100; //function prototypes bool openFile(ifstream &); void readData(ifstream &, int [], int &); void printData(const int [], int); void sum(const int[], int); void removeItem(int[], int &, int); int main() { ifstream inFile; int list[CAP], size = 0; if (!openFile(inFile)) { cout << "Program terminating!! File not found!" << endl; return -1; } //read the data from the file readData(inFile, list, size); inFile.close(); cout << "Data in file:" <<...
C++ comment code Comment the following code #include <iostream> using namespace std; class Node { public: Node(int val); int value; Node* next; }; Node::Node(int val){ value = val; } class List { public: List(); // Uncomment the line below once you're ready List(List &other); void push_front(int value); bool pop_front(int &value); void push_back(int value); bool pop_back(int &value); int at(int index); void insert_at(int index, int value); void remove_at(int index); int size(); private: // other members you may have used Node* head; Node*...
#include <iostream> using namespace std; const int SIZE = 10; void displayGreaterThan(int[], int); void displaySmallerThan(int[],int); void displayArrayContent(int[]); void displayLargestValue(int[]); void displaySmallestValue(int[]); int main(){ int number; int numbers[SIZE] = {9,1,90,98,53,22,76,29,37,65}; cout <<"Enter a number: "; cin >> number; cout << endl; displayGreaterThan(numbers,number); cout << endl; displaySmallerThan(numbers,number); cout << endl; displayArrayContent(numbers); cout << endl; displayLargestValue(numbers); cout << endl; displaySmallestValue(numbers); cout << endl; return 0; } void displayGreaterThan(int value[],int num){ cout << " All larger value(s)than" <<...
#include <iostream> #include <cstdlib> using namespace std; int **dynArray(int row, int cols) { int **myPtr; int lab[4]; myPtr = new int *[row]; for(int i = 0; i < row; i++) myPtr[i] = new int[lab[i]]; for(int i = 0; i<row ; i++) if(myPtr[i] == 0) cout<<"empty"; return myPtr; } void getinput(int ID,int &Station,int &labnumb) { cout<<" Enter your ID number: "<<endl; cin>>ID; cout<<" Enter your station number: "<<endl; cin>>Station; cout<<" Enter your lab number: "<<endl; cin>>labnumb; return; } void logout(int ID,int...
#include<iostream> #include<string> #include<iomanip> using namespace std; /* ********* Class Car ************* ********************************* */ class Car { private: string reportingMark; int carNumber; string kind; bool loaded; string choice; string destination; public: Car() { reportingMark = ""; carNumber = 0; kind = "Others"; loaded = 0; destination = "NONE"; } ~Car() { } void setUpCar(string &reportingMark, int &carNumber, string &kind, bool &loaded, string &destination); }; void input(string &reportingMark, int &carNumber, string &kind, bool &loaded,string choice, string &destination); void output(string &reportingMark, int &carNumber,...
#include "stdafx.h" #include <iostream> using namespace std; class dateType { private: int dmonth; int dday; int dyear; public: void setdate (int month, int day, int year); int getday()const; int getmonth()const; int getyear()const; int printdate()const; bool isleapyear(int year); dateType (int month=0, int day=0, int year=0); }; void dateType::setdate(int month, int day, int year) { int numofdays; if (year<=2008) { dyear=year;...
#include <iostream> using namespace std; bool binarySearch(int arr[], int start, int end, int target){ //your code here } void fill(int arr[], int count){ for(int i = 0; i < count; i++){ cout << "Enter number: "; cin >> arr[i]; } } void display(int arr[], int count){ for(int i = 0; i < count; i++){ cout << arr[i] << endl; } } int main() { cout << "How many items: "; int count; cin >> count; int * arr = new...