0% found this document useful (0 votes)
58 views33 pages

DGraph Class Implementation Guide

Uploaded by

quan.buivietanh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views33 pages

DGraph Class Implementation Guide

Uploaded by

quan.buivietanh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

12/9/24, 11:37 AM Graph: Attempt review | BK-LMS

Status Finished
Started Monday, 25 November 2024, 12:38 PM
Completed Saturday, 7 December 2024, 10:43 PM
Duration 12 days 10 hours
Grade 10.00 out of 10.00 (100%)

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 1/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS

Question 1
Correct

Mark 1.00 out of 1.00

Template class DGraph representing a directed graph with type T with the initialized frame. It has attribute VertexNode*
nodeList, which is the head of a singly linked list, representing a list of vertex of this graph.
This class inlcudes 2 classes: VertexNode and Edge.
- Class VertexNode representing a vertex in graph. It has some attributes:
+ T vertex: the vertex's value.
+ Edge* adList: a singly linked list representing the adjacent edges that have this vertex as their starting vertex (from).
- Class Edge representing an edge in graph. It has some attributes:
+ VertexNode* fromNode - VertexNode* toNode: represents the starting vertex (from) and ending vertex (to) of this edge.
+ float weight: edge's weight.

Requirements: In class VertexNode, implement methods getEdge, connectTo, addAdjacentEdge, and removeTo.
Descriptions for each method are provided below. Ensure that all four methods are fully implemented before checking.

template <class T>


class DGraph {
public:
class VertexNode; // Forward declaration
class Edge; // Forward declaration
protected:
VertexNode* nodeList; //list of vertexNode of DGraph
int countVertex;
int countEdge;
public:
DGraph() {
this->nodeList = nullptr;
this->countEdge = 0;
this->countVertex = 0;
}
~DGraph() {};
VertexNode* getVertexNode(T vertex);
void add(T vertex);

void connect(T from, T to, float weight=0);

void removeVertex(T removeVertex);


bool removeEdge(T from, T to);
string shape();
bool empty();
void clear();
void printGraph();

public:
class VertexNode {
private:
T vertex;

Edge* adList; //list of adjacent edge of this vertex
VertexNode* next;

friend class Edge;


friend class DGraph;

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 2/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS
public:

VertexNode(T vertex, Edge* adList = nullptr, VertexNode* next = nullptr) {


this->vertex = vertex;
this->adList = adList;
this->next = next;
}
string toString();
void addAdjacentEdge(Edge* newEdge);
bool connectTo(VertexNode* toNode, float weight = 0);
bool removeTo(VertexNode* toNode);
Edge* getEdge(VertexNode* toNode);
};

class Edge {
private:
VertexNode* fromNode;
VertexNode* toNode;
float weight;
Edge* next;

friend class VertexNode;


friend class DGraph;
public:
Edge(VertexNode* fromNode, VertexNode* toNode, float weight = 0.0, Edge* next = nullptr) {
this->fromNode = fromNode;
this->toNode = toNode;
this->weight = weight;
this->next = next;
}
string toString();

};
};
For example:

Test Result

DGraph<int>::VertexNode* node0 = new DGraph<int>::VertexNode(0); E(0,1,12.3)


DGraph<int>::VertexNode* node1 = new DGraph<int>::VertexNode(1); E(1,3,176)
DGraph<int>::VertexNode* node2 = new DGraph<int>::VertexNode(2);
DGraph<int>::VertexNode* node3 = new DGraph<int>::VertexNode(3);

node0->connectTo(node1, 12.3);
node0->connectTo(node2, 13.3);
node0->connectTo(node3, 14);
node1->connectTo(node3, 176);

cout << node0->getEdge(node1)->toString() << endl;


cout << node1->getEdge(node3)->toString() << endl;

delete node0;
delete node1;
delete node2;
delete node3; 

Answer: (penalty regime: 0 %)

Reset answer

1 template<class T>
https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 3/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS
1 template<class T>
2 ▼ typename DGraph<T>::Edge* DGraph<T>::VertexNode::getEdge(VertexNode* toNode) {
3 //TODO: Iterate through the adjacency list of this vertex
4 // checking if there exists an edge with this vertex as the starting vertex
5 // and "toNode" as the ending vertex.
6 // If not return nullptr, else return that edge.
7 Edge* current = this->adList;
8▼ while(current != nullptr){
9▼ if(current->toNode->vertex == toNode->vertex){
10 return current;
11 }
12 current = current->next;
13 }
14 return nullptr;
15 }
16
17 template<class T>
18 ▼ void DGraph<T>::VertexNode::addAdjacentEdge(Edge* newEdge) {
19 //TODO: add newEdge to adjacency list of this vertex.
20 newEdge->next = this->adList;
21 this->adList = newEdge;
22
23 }
24
25 template<class T>
26 ▼ bool DGraph<T>::VertexNode::connectTo(VertexNode* toNode, float weight) {
27 //TODO: get edge from this node to "toNode".
28 Edge* temp = this->getEdge(toNode);
29 //TODO: If the edge is not existed, create a new Edge and add it to the adjacency list.
30 // If the edge is existed, update its weight.
31 ▼ if(temp == nullptr){
32 this->adList = new Edge(this, toNode, weight, adList);
33 return true;
34 }
35 temp->weight = weight;
36 return false;
37 //TODO: Return true if a new Edge is created; otherwise, return false.
38
39
40 }
41
42 template<class T>
43 ▼ bool DGraph<T>::VertexNode::removeTo(VertexNode *toNode) {
44 //TODO: remove the edge with "toNode" as the ending vertex from this node's adjacency list.
45 Edge* temp = this->getEdge(toNode);
46 if(temp == NULL)
47 return false;
48
49 ▼ if (temp == this->adList){
50 this->adList = temp->next;
51 delete temp;
52 return true;

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 4/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS

Test Expected Got

 DGraph<int>::VertexNode* node0 = new DGraph<int>::VertexNode(0); E(0,1,12.3) E(0,1,12.3) 


DGraph<int>::VertexNode* node1 = new DGraph<int>::VertexNode(1); E(1,3,176) E(1,3,176)
DGraph<int>::VertexNode* node2 = new DGraph<int>::VertexNode(2);
DGraph<int>::VertexNode* node3 = new DGraph<int>::VertexNode(3);

node0->connectTo(node1, 12.3);
node0->connectTo(node2, 13.3);
node0->connectTo(node3, 14);
node1->connectTo(node3, 176);

cout << node0->getEdge(node1)->toString() << endl;


cout << node1->getEdge(node3)->toString() << endl;

delete node0;
delete node1;
delete node2;
delete node3;

 DGraph<char>::VertexNode* nodeA = new DGraph<char>::VertexNode('A'); E(E,A,0) E(E,A,0) 


DGraph<char>::VertexNode* nodeB = new DGraph<char>::VertexNode('B'); E(C,C,0.54) E(C,C,0.54)
DGraph<char>::VertexNode* nodeC = new DGraph<char>::VertexNode('C'); E(A,B,0) E(A,B,0)
DGraph<char>::VertexNode* nodeD = new DGraph<char>::VertexNode('D'); E(A,C,29.4) E(A,C,29.4)
DGraph<char>::VertexNode* nodeE = new DGraph<char>::VertexNode('E'); Edge doesn't Edge doesn't
exist! exist!
nodeA->connectTo(nodeB); Edge doesn't Edge doesn't
nodeA->connectTo(nodeC, 29.4); exist! exist!
nodeA->connectTo(nodeD, 30.4);
nodeB->connectTo(nodeD, 19.75);
nodeC->connectTo(nodeC, 0.54);
nodeE->connectTo(nodeA);

cout << (nodeE->getEdge(nodeA) ? nodeE->getEdge(nodeA)->toString() :


"Edge doesn't exist!") << endl;
cout << (nodeC->getEdge(nodeC) ? nodeC->getEdge(nodeC)->toString() :
"Edge doesn't exist!") << endl;
nodeE->removeTo(nodeA);
nodeC->removeTo(nodeC);

cout << (nodeA->getEdge(nodeB) ? nodeA->getEdge(nodeB)->toString() :


"Edge doesn't exist!") << endl;
cout << (nodeA->getEdge(nodeC) ? nodeA->getEdge(nodeC)->toString() :
"Edge doesn't exist!") << endl;
cout << (nodeE->getEdge(nodeA) ? nodeE->getEdge(nodeA)->toString() :
"Edge doesn't exist!") << endl;
cout << (nodeC->getEdge(nodeC) ? nodeC->getEdge(nodeC)->toString() :
"Edge doesn't exist!") << endl;

delete nodeA;
delete nodeB;
delete nodeC;
delete nodeD;
delete nodeE;

Passed all tests! 

Correct

Marks for this submission: 1.00/1.00.

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 5/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS

Question 2
Correct

Mark 1.00 out of 1.00

Template class DGraph representing a directed graph with type T with the initialized frame. It has attribute VertexNode*
nodeList, which is the head of a singly linked list, representing list of vertex of this graph.
This class inlcudes 2 classes: VertexNode and Edge.
- Class VertexNode representing a vertex in graph. It has some attributes:
+ T vertex: the vertex's value.
+ Edge* adList: a singly linked list representing the adjacent edges that have this vertex as their starting vertex (from).
- Class Edge representing an edge in graph. It has some attributes:
+ VertexNode* fromNode - VertexNode* toNode: represents the starting vertex (from) and ending vertex (to) of this edge.
+ float weight: edge's weight.

Requirements: In class DGraph, implement methods getVertexNode, add and connect. Descriptions for each method are
provided below. Ensure that all three methods are fully implemented before checking.

Notes: You can use the methods from the previous exercises without needing to implement them again.

template <class T>


class DGraph {
public:
class VertexNode; // Forward declaration
class Edge; // Forward declaration
protected:
VertexNode* nodeList; //list of vertexNode of DGraph
int countVertex;
int countEdge;
public:
DGraph() {
this->nodeList = nullptr;
this->countEdge = 0;
this->countVertex = 0;
}
~DGraph() {};
VertexNode* getVertexNode(T vertex);
void add(T vertex);

void connect(T from, T to, float weight=0);

void removeVertex(T removeVertex);


bool removeEdge(T from, T to);
string shape();
bool empty();
void clear();
void printGraph();

public:
class VertexNode {

private:
T vertex;
Edge* adList; //list of adjacent edge of this vertex
VertexNode* next;

friend class Edge;

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 6/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS
friend class DGraph;
public:

VertexNode(T vertex, Edge* adList = nullptr, VertexNode* next = nullptr) {


this->vertex = vertex;
this->adList = adList;
this->next = next;
}
string toString();
void addAdjacentEdge(Edge* newEdge);
bool connectTo(VertexNode* toNode, float weight = 0);
bool removeTo(VertexNode* toNode);
Edge* getEdge(VertexNode* toNode);
};

class Edge {
private:
VertexNode* fromNode;
VertexNode* toNode;
float weight;
Edge* next;

friend class VertexNode;


friend class DGraph;
public:
Edge(VertexNode* fromNode, VertexNode* toNode, float weight = 0.0, Edge* next = nullptr) {
this->fromNode = fromNode;
this->toNode = toNode;
this->weight = weight;
this->next = next;
}
string toString();

};
};
For example:

Test Result

DGraph<int> graph; ==================================================


for(int i = 0; i < 6; i++) graph.add(i); Number of vertices: 6
graph.printGraph(); V(0)
V(1)
V(2)
V(3)
V(4)
V(5)
------------------------------
Number of edges: 0
==================================================

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 7/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS

Test Result

DGraph<int> graph; ==================================================


for(int i = 0; i < 6; i++) graph.add(i); Number of vertices: 6
V(0)
graph.connect(1, 2, 40); V(1)
graph.connect(1, 3, 6.9); V(2)
graph.connect(4, 5, 27); V(3)
graph.connect(3, 2, 2.1); V(4)
graph.connect(0, 2, 11.2); V(5)
graph.connect(0, 5, 67); ------------------------------
graph.connect(2, 1, 19.75); Number of edges: 7
E(0,2,11.2)
graph.printGraph(); E(0,5,67)
E(1,2,40)
E(1,3,6.9)
E(2,1,19.75)
E(3,2,2.1)
E(4,5,27)
==================================================

Answer: (penalty regime: 0 %)

Reset answer

1 template<class T>
2 ▼ typename DGraph<T>::VertexNode* DGraph<T>::getVertexNode(T vertex) {
3 //TODO: Iterate through the Node list of the graph
4 // check if any vertexNode contains vertex.
5 // If such a vertexNode exists, return it; otherwise, return nullptr.
6 VertexNode* access = this->nodeList;
7 while(access != nullptr)
8 ▼ {
9 if(access->vertex == vertex)
10 ▼ {
11 return access;
12 }
13 access = access->next;
14 }
15 return nullptr;
16 }
17 template<class T>
18 ▼ void DGraph<T>::add(T vertex) {
19 //TODO: create a new vertexNode with vertex.
20
21 //TODO: add new vertexNode to the end of Node list of the graph.
22
23 //TODO: increase the countVertex.
24 if(this->countVertex == 0)
25 ▼ {
26 this->countVertex = 1;
27 this->nodeList = new VertexNode(vertex);
28 return;
29 }
30
31 VertexNode* access = this->nodeList;
32 while(access->next != nullptr)
33 access = access->next;
34
35 access->next = new VertexNode(vertex);
36 this->countVertex++;
37

38 }
39 template <class T>
40 ▼ void DGraph<T>::connect(T from, T to, float weight) {
41 //TODO: get vertexNode with "from" and vertexNode with "to".
42
43 //TODO: If either of the two vertexNode objects does not exist,
44 // throw an exception: VertexNotFoundException("Vertex doesn't exist!").
https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 8/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS
45
46 //TODO: connect "from" vertexNode to "to" vertexNode.
47 // If a new edge is created, increase the countEdge.
48 VertexNode* nod1 = this->getVertexNode(from);
49 VertexNode* nod2 = this->getVertexNode(to);
50
51 if(nod1 == nullptr || nod2 == nullptr)
52 throw VertexNotFoundException("Vertex doesn't exist!");

Test Expected Got

 DGraph<int> graph; ================================================== ===========================================


for(int i = 0; i < Number of vertices: 6 Number of vertices: 6
6; i++) V(0) V(0)
graph.add(i); V(1) V(1)
graph.printGraph(); V(2) V(2)
V(3) V(3)
V(4) V(4)
V(5) V(5)
------------------------------ ------------------------------
Number of edges: 0 Number of edges: 0
================================================== ===========================================

 DGraph<int> graph; ================================================== ===========================================


for(int i = 0; i < Number of vertices: 6 Number of vertices: 6
6; i++) V(0) V(0)
graph.add(i); V(1) V(1)
V(2) V(2)
graph.connect(1, 2, V(3) V(3)
40); V(4) V(4)
graph.connect(1, 3, V(5) V(5)
6.9); ------------------------------ ------------------------------
graph.connect(4, 5, Number of edges: 7 Number of edges: 7
27); E(0,2,11.2) E(0,2,11.2)
graph.connect(3, 2, E(0,5,67) E(0,5,67)
2.1); E(1,2,40) E(1,2,40)
graph.connect(0, 2, E(1,3,6.9) E(1,3,6.9)
11.2); E(2,1,19.75) E(2,1,19.75)
graph.connect(0, 5, E(3,2,2.1) E(3,2,2.1)
67); E(4,5,27) E(4,5,27)
graph.connect(2, 1, ================================================== ===========================================
19.75);

graph.printGraph();

Passed all tests! 

Correct
Marks for this submission: 1.00/1.00.

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 9/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS

Question 3
Correct

Mark 1.00 out of 1.00

Template class DGraph representing a directed graph with type T with the initialized frame. It has attribute VertexNode*
nodeList, which is the head of a singly linked list, representing list of vertex of this graph.
This class inlcudes 2 classes: VertexNode and Edge.
- Class VertexNode representing a vertex in graph. It has some attributes:
+ T vertex: the vertex's value.
+ Edge* adList: a singly linked list representing the adjacent edges that have this vertex as their starting vertex (from).
- Class Edge representing an edge in graph. It has some attributes:
+ VertexNode* fromNode - VertexNode* toNode: represents the starting vertex (from) and ending vertex (to) of this edge.
+ float weight: edge's weight.

Requirements: Implement methods removeEdge and removeVertex. Descriptions for each method are provided below.

Notes:

- The removeTo method is used to delete an edge that ends at the vertex "toNode" from the adjacency list of the current
vertex. Students should use this method when implementing removeEdge and removeVertex.

- You can use the methods from the previous exercises without needing to implement them again.

template <class T>


class DGraph {
public:
class VertexNode; // Forward declaration
class Edge; // Forward declaration
protected:
VertexNode* nodeList; //list of vertexNode of DGraph
int countVertex;
int countEdge;
public:
DGraph() {
this->nodeList = nullptr;
this->countEdge = 0;
this->countVertex = 0;
}
~DGraph() {};
VertexNode* getVertexNode(T vertex);
void add(T vertex);

void connect(T from, T to, float weight=0);

void removeVertex(T removeVertex);


bool removeEdge(T from, T to);
string shape();
bool empty();
void clear();
void printGraph();

public:
class VertexNode {
private:
T vertex;
Edge* adList; //list of adjacent edge of this vertex

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 10/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS
VertexNode* next;

friend class Edge;


friend class DGraph;
public:

VertexNode(T vertex, Edge* adList = nullptr, VertexNode* next = nullptr) {


this->vertex = vertex;
this->adList = adList;
this->next = next;
}
string toString();
void addAdjacentEdge(Edge* newEdge);
bool connectTo(VertexNode* toNode, float weight = 0);
bool removeTo(VertexNode* toNode);
Edge* getEdge(VertexNode* toNode);
};

class Edge {
private:
VertexNode* fromNode;
VertexNode* toNode;
float weight;
Edge* next;

friend class VertexNode;


friend class DGraph;
public:
Edge(VertexNode* fromNode, VertexNode* toNode, float weight = 0.0, Edge* next = nullptr) {
this->fromNode = fromNode;
this->toNode = toNode;
this->weight = weight;
this->next = next;
}
string toString();

};
};
For example:

Test Result

DGraph<int> graph; ==================================================


Number of vertices: 6
for(int i = 0; i < 6; i++) graph.add(i); V(0)
V(1)
graph.connect(1, 2, 40); V(2)
graph.connect(1, 3, 6.9); V(3)
graph.connect(4, 5, 27); V(4)
graph.connect(3, 2, 2.1); V(5)
graph.connect(1, 2, 11.2); ------------------------------
graph.connect(1, 3, 67); Number of edges: 1
E(3,2,2.1)
graph.removeEdge(1, 2); ==================================================

graph.removeEdge(4, 5);
graph.removeEdge(1, 3);

graph.printGraph();

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 11/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS

Test Result

DGraph<int> graph; ==================================================


Number of vertices: 5
for(int i = 0; i < 6; i++) graph.add(i); V(0)
V(1)
graph.connect(1, 2, 40); V(3)
graph.connect(1, 3, 6.9); V(4)
graph.connect(4, 5, 27); V(5)
graph.connect(3, 2, 2.1); ------------------------------
graph.connect(1, 2, 11.2); Number of edges: 2
E(1,3,6.9)
graph.removeVertex(2); E(4,5,27)
==================================================
graph.printGraph();

Answer: (penalty regime: 0 %)

Reset answer

1 template <class T>


2 ▼ bool DGraph<T>::removeEdge(T from, T to) {
3 //TODO: get vertexNode with "from" and vertexNode with "to".
4
5 //TODO: If either of the two vertexNode objects does not exist,
6 // throw an exception: VertexNotFoundException("Vertex doesn't exist!").
7
8 //TODO: Delete the edge between the "from" vertexNode and the "to" vertexNode. (use removeTo method)
9 // If success return true and decrement the countEdge; otherwise, return false;
10 VertexNode* nod1 = this->getVertexNode(from);
11 VertexNode* nod2 = this->getVertexNode(to);
12
13 if(nod1 == nullptr || nod2 == nullptr)
14 throw VertexNotFoundException("Vertex doesn't exist!");
15
16 if(nod1->removeTo(nod2))
17 ▼ {
18 this->countEdge--;
19 return true;
20 }
21
22 return false;
23
24 }
25 template <class T>
26 ▼ void DGraph<T>::removeVertex(T removeVertex) {
27
28 VertexNode* found = this->getVertexNode(removeVertex);
29
30 ▼ if (found == nullptr) {
31 throw VertexNotFoundException("Vertex doesn't exist!");
32 }
33
34 VertexNode* current = this->nodeList;
35 ▼ while (current != nullptr) {
36 ▼ if (current != found) {
37 ▼ if (current->removeTo(found)) {
38 this->countEdge--;
39 }
40 }
41 current = current->next;
42 } 
43
44 Edge* edge = found->adList;
45 ▼ while (edge != nullptr) {
46 Edge* nextEdge = edge->next;
47 ▼ if (found->removeTo(edge->toNode)) {
48 this->countEdge--;
49 }
50 edge = nextEdge;
https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 12/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS
50 edge = nextEdge;
51 }
52

Test Expected Got

 DGraph<int> graph; ================================================== ========================================


Number of vertices: 6 Number of vertices: 6
for(int i = 0; i < 6; V(0) V(0)
i++) graph.add(i); V(1) V(1)
V(2) V(2)
graph.connect(1, 2, V(3) V(3)
40); V(4) V(4)
graph.connect(1, 3, V(5) V(5)
6.9); ------------------------------ ------------------------------
graph.connect(4, 5, Number of edges: 1 Number of edges: 1
27); E(3,2,2.1) E(3,2,2.1)
graph.connect(3, 2, ================================================== ========================================
2.1);
graph.connect(1, 2,
11.2);
graph.connect(1, 3,
67);

graph.removeEdge(1,
2);
graph.removeEdge(4,
5);
graph.removeEdge(1,
3);

graph.printGraph();

 DGraph<int> graph; ================================================== ========================================


Number of vertices: 5 Number of vertices: 5
for(int i = 0; i < 6; V(0) V(0)
i++) graph.add(i); V(1) V(1)
V(3) V(3)
graph.connect(1, 2, V(4) V(4)
40); V(5) V(5)
graph.connect(1, 3, ------------------------------ ------------------------------
6.9); Number of edges: 2 Number of edges: 2
graph.connect(4, 5, E(1,3,6.9) E(1,3,6.9)
27); E(4,5,27) E(4,5,27)
graph.connect(3, 2, ================================================== ========================================
2.1);
graph.connect(1, 2,
11.2);

graph.removeVertex(2);

graph.printGraph();

Passed all tests! 

Correct
Marks for this submission: 1.00/1.00. 

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 13/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS

Question 4
Correct

Mark 1.00 out of 1.00

Template class DGraph representing a directed graph with type T with the initialized frame. It has attribute VertexNode*
nodeList, which is the head of a singly linked list, representing list of vertex of this graph.
This class inlcudes 2 classes: VertexNode and Edge.
- Class VertexNode representing a vertex in graph. It has some attributes:
+ T vertex: the vertex's value.
+ Edge* adList: a singly linked list representing the adjacent edges that have this vertex as their starting vertex (from).
- Class Edge representing an edge in graph. It has some attributes:
+ VertexNode* fromNode - VertexNode* toNode: represents the starting vertex (from) and ending vertex (to) of this edge.
+ float weight: edge's weight.

Requirements: Implement methods shape, empty and clear. Descriptions for each method are provided below.

Notes: You can use the methods from the previous exercises without needing to implement them again.

template <class T>


class DGraph {
public:
class VertexNode; // Forward declaration
class Edge; // Forward declaration
protected:
VertexNode* nodeList; //list of vertexNode of DGraph
int countVertex;
int countEdge;
public:
DGraph() {
this->nodeList = nullptr;
this->countEdge = 0;
this->countVertex = 0;
}
~DGraph() {};
VertexNode* getVertexNode(T vertex);
void add(T vertex);

void connect(T from, T to, float weight=0);

void removeVertex(T removeVertex);


bool removeEdge(T from, T to);
string shape();
bool empty();
void clear();
void printGraph();

public:
class VertexNode {
private:

T vertex;
Edge* adList; //list of adjacent edge of this vertex
VertexNode* next;

friend class Edge;


friend class DGraph;

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 14/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS
public:

VertexNode(T vertex, Edge* adList = nullptr, VertexNode* next = nullptr) {


this->vertex = vertex;
this->adList = adList;
this->next = next;
}
string toString();
void addAdjacentEdge(Edge* newEdge);
bool connectTo(VertexNode* toNode, float weight = 0);
bool removeTo(VertexNode* toNode);
Edge* getEdge(VertexNode* toNode);
};

class Edge {
private:
VertexNode* fromNode;
VertexNode* toNode;
float weight;
Edge* next;

friend class VertexNode;


friend class DGraph;
public:
Edge(VertexNode* fromNode, VertexNode* toNode, float weight = 0.0, Edge* next = nullptr) {
this->fromNode = fromNode;
this->toNode = toNode;
this->weight = weight;
this->next = next;
}
string toString();

};
};
For example:

Test Result

DGraph<int> graph; [Vertices: 6, Edges: 2]

for(int i = 0; i < 6; i++) graph.add(i);

graph.connect(1, 2, 40);
graph.connect(1, 3, 6.9);
graph.connect(4, 5, 27);
graph.connect(3, 2, 2.1);
graph.connect(1, 2, 11.2);
graph.connect(1, 3, 67);

graph.removeEdge(1, 2);
graph.removeEdge(4, 5);

cout << graph.shape() << endl;

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 15/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS

Test Result

DGraph<int> graph; [Vertices: 0, Edges: 0]


Graph is empty!
for(int i = 0; i < 6; i++) graph.add(i);

graph.connect(1, 2, 40);
graph.connect(1, 3, 6.9);
graph.connect(4, 5, 27);
graph.connect(3, 2, 2.1);
graph.connect(1, 2, 11.2);
graph.connect(1, 3, 67);

graph.clear();
cout << graph.shape() << endl;
cout << (graph.empty() ? "Graph is empty!" : "Graph is not empty!") << endl;

Answer: (penalty regime: 0 %)

Reset answer

1 template<class T>
2 ▼ string DGraph<T>::shape() {
3 //TODO: return the string with format: [Vertices: <numOfVertex>, Edges: <numOfEdge>]
4 stringstream os;
5 os <<"[Vertices: " << this->countVertex <<", Edges: " << this->countEdge << "]";
6 return os.str();
7 }
8 template<class T>
9 ▼ bool DGraph<T>::empty() {
10 //TODO: return if graph is empty (it doesn't have any vertex and edge)
11 return this->countVertex == 0;
12 }
13 template<class T>
14 ▼ void DGraph<T>::clear() {
15 //TODO: remove all edges and vertices of graph.
16 while(this->nodeList != nullptr)
17 ▼ {
18 Edge* temp = this->nodeList->adList;
19 while(temp != nullptr)
20 ▼ {
21 Edge* next = temp->next;
22 delete temp;
23 temp = next;
24 }
25 VertexNode* toDel = this->nodeList;
26 this->nodeList = this->nodeList->next;
27 delete toDel;
28 }
29 this->countEdge = 0;
30 this->countVertex = 0;
31 }
32

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 16/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS

Test Expected Got

 DGraph<int> graph; [Vertices: 6, Edges: [Vertices: 6, Edges: 


2] 2]
for(int i = 0; i < 6; i++) graph.add(i);

graph.connect(1, 2, 40);
graph.connect(1, 3, 6.9);
graph.connect(4, 5, 27);
graph.connect(3, 2, 2.1);
graph.connect(1, 2, 11.2);
graph.connect(1, 3, 67);

graph.removeEdge(1, 2);
graph.removeEdge(4, 5);

cout << graph.shape() << endl;

 DGraph<int> graph; [Vertices: 0, Edges: [Vertices: 0, Edges: 


0] 0]
for(int i = 0; i < 6; i++) graph.add(i); Graph is empty! Graph is empty!

graph.connect(1, 2, 40);
graph.connect(1, 3, 6.9);
graph.connect(4, 5, 27);
graph.connect(3, 2, 2.1);
graph.connect(1, 2, 11.2);
graph.connect(1, 3, 67);

graph.clear();
cout << graph.shape() << endl;
cout << (graph.empty() ? "Graph is empty!" : "Graph is not
empty!") << endl;

Passed all tests! 

Correct
Marks for this submission: 1.00/1.00.

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 17/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS

Question 5
Correct

Mark 1.00 out of 1.00

Implement Breadth-first search

Adjacency *BFS(int v);

where Adjacency is a structure to store list of number.

#include <iostream>
#include <list>
using namespace std;

class Adjacency
{
private:
list<int> adjList;
int size;
public:
Adjacency() {}
Adjacency(int V) {}
void push(int data)
{
adjList.push_back(data);
size++;
}
void print()
{
for (auto const &i : adjList)
cout << " -> " << i;
}
void printArray()
{
for (auto const &i : adjList)
cout << i << " ";
}
int getSize() { return adjList.size(); }
int getElement(int idx)
{
auto it = adjList.begin();
advance(it, idx);
return *it;
}
};

And Graph is a structure to store a graph (see in your answer box)

For example:

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 18/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS

Test Result

int V = 6; 0 1 2 3 4 5
int visited = 0;

Graph g(V);
Adjacency* arr = new Adjacency(V);
int edge[][2] = {{0,1},{0,2},{1,3},{1,4},{2,4},{3,4},{3,5},{4,5}};

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


{
g.addEdge(edge[i][0], edge[i][1]);
}

arr = g.BFS(visited);
arr->printArray();
delete arr;

int V = 6; 2 0 4 1 3 5
int visited = 2;

Graph g(V);
Adjacency* arr = new Adjacency(V);
int edge[][2] = {{0,1},{0,2},{1,3},{1,4},{2,4},{3,4},{3,5},{4,5}};

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


{
g.addEdge(edge[i][0], edge[i][1]);
}

arr = g.BFS(visited);
arr->printArray();
delete arr;

Answer: (penalty regime: 0 %)

Reset answer

1 class Graph
2 ▼ {
3 private:
4 int V;
5 Adjacency *adj;
6
7 public:
8 Graph(int V)
9 ▼ {
10 this->V = V;
11 adj = new Adjacency[V];
12 }
13
14 void addEdge(int v, int w)
15 ▼ {
16 adj[v].push(w);
17 adj[w].push(v);
18 }
19
20 void printGraph()
21 ▼ {
22 for (int v = 0; v < V; ++v)
23 ▼ {

24 cout << "\nAdjacency list of vertex " << v << "\nhead ";
25 adj[v].print();
26 }
27 }
28
29 Adjacency *BFS(int v)
30 ▼ {
// i
https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 19/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS
31 // v is a vertex we start BFS
32 Adjacency* result = new Adjacency();
33 bool visited[V] = {false};
34 list<int> q ;
35 q.push_back(v);
36 visited[v] = true;
37 ▼ while(!q.empty()){
38 int curr = q.front();
39 q.pop_front();
40 result->push(curr);
41
42 ▼ for(int i = 0; i < adj[curr].getSize(); i++){
43 ▼ if(!visited[adj[curr].getElement(i)]){
44 q.push_back(adj[curr].getElement(i));
45 visited[adj[curr].getElement(i)] = true;
46 }
47 }
48 }
49 return result;
50 }
51
52

Test Expected Got

 int V = 6; 0 1 2 3 4 5 0 1 2 3 4 5 
int visited = 0;

Graph g(V);
Adjacency* arr = new Adjacency(V);
int edge[][2] = {{0,1},{0,2},{1,3},{1,4},{2,4},{3,4},{3,5},{4,5}};

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


{
g.addEdge(edge[i][0], edge[i][1]);
}

arr = g.BFS(visited);
arr->printArray();
delete arr;

 int V = 6; 2 0 4 1 3 5 2 0 4 1 3 5 
int visited = 2;

Graph g(V);
Adjacency* arr = new Adjacency(V);
int edge[][2] = {{0,1},{0,2},{1,3},{1,4},{2,4},{3,4},{3,5},{4,5}};

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


{
g.addEdge(edge[i][0], edge[i][1]);
}

arr = g.BFS(visited);
arr->printArray();
delete arr;

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 20/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS

Test Expected Got

 int V = 8, visited = 5; 5 2 0 1 6 3 4 5 2 0 1 6 3 4 
7 7
Graph g(V);
Adjacency *arr;
int edge[][2] = {{0,1}, {0,2}, {0,3}, {0,4}, {1,2}, {2,5}, {2,6}, {4,6},
{6,7}};
for(int i = 0; i < 9; i++)
{
\tg.addEdge(edge[i][0], edge[i][1]);
}

// g.printGraph();
// cout << endl;
arr = g.BFS(visited);
arr->printArray();
delete arr;

Passed all tests! 

Correct
Marks for this submission: 1.00/1.00.

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 21/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS

Question 6
Correct

Mark 1.00 out of 1.00

Implement Depth-first search

Adjacency *DFS(int v);

where Adjacency is a structure to store list of number.

#include <iostream>
#include <list>
using namespace std;

class Adjacency
{
private:
list<int> adjList;
int size;
public:
Adjacency() {}
Adjacency(int V) {}
void push(int data)
{
adjList.push_back(data);
size++;
}
void print()
{
for (auto const &i : adjList)
cout << " -> " << i;
}
void printArray()
{
for (auto const &i : adjList)
cout << i << " ";
}
int getSize() { return adjList.size(); }
int getElement(int idx)
{
auto it = adjList.begin();
advance(it, idx);
return *it;
}
};

And Graph is a structure to store a graph (see in your answer box)

For example:

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 22/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS

Test Result

int V = 8, visited = 0; 0 1 2 5 6 4 7 3

Graph g(V);
Adjacency *arr;
int edge[][2] = {{0,1}, {0,2}, {0,3}, {0,4}, {1,2}, {2,5}, {2,6}, {4,6}, {6,7}};
for(int i = 0; i < 9; i++)
{
g.addEdge(edge[i][0], edge[i][1]);
}

// g.printGraph();
// cout << endl;
arr = g.DFS(visited);
arr->printArray();
delete arr;

Answer: (penalty regime: 0 %)

Reset answer

1 class Graph
2▼ {
3 private:
4 int V;
5 Adjacency *adj;
6 public:
7 Graph(int V)
8▼ {
9 this->V = V;
10 adj = new Adjacency[V];
11 }
12
13 void addEdge(int v, int w)
14 ▼ {
15 adj[v].push(w);
16 adj[w].push(v);
17 }
18
19 void printGraph()
20 ▼ {
21 for (int v = 0; v < V; ++v)
22 ▼ {
23 cout << "\nAdjacency list of vertex " << v << "\nhead ";
24 adj[v].print();
25 }
26 }
27
28 Adjacency *DFS(int v)
29 ▼ {
30 // v is a vertex we start DFS
31 bool* visited = new bool[this->V];
32 for(int i = 0 ; i < this->V ; ++i)
33 visited[i] = false;
34
35
36 list<int> st;
37 Adjacency* result = new Adjacency();
38
39 st.push_back(v);
40 
41
42 while(!st.empty())
43 ▼ {
44 int curr = st.back();
45 st.pop_back();
46
47 if(!visited[curr])
48 {
https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 23/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS
48 ▼ {
49 visited[curr] = true;
50 result->push(curr);
51 ▼ for (int i = adj[curr].getSize() - 1; i >= 0; --i) {
52 int neighbor = adj[curr].getElement(i);
53 ▼ if (!visited[neighbor]) {
54 st.push_back(neighbor);
55 }
56 }
57 }
58
59 }
60 delete[]visited;
61 return result;
62 }

Test Expected Got

 int V = 8, visited = 0; 0 1 2 5 6 4 7 0 1 2 5 6 4 7 
3 3
Graph g(V);
Adjacency *arr;
int edge[][2] = {{0,1}, {0,2}, {0,3}, {0,4}, {1,2}, {2,5}, {2,6}, {4,6},
{6,7}};
for(int i = 0; i < 9; i++)
{
\tg.addEdge(edge[i][0], edge[i][1]);
}

// g.printGraph();
// cout << endl;
arr = g.DFS(visited);
arr->printArray();
delete arr;

Passed all tests! 

Correct
Marks for this submission: 1.00/1.00.

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 24/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS

Question 7
Correct

Mark 1.00 out of 1.00

The relationship between a group of people is represented by an adjacency-list friends. If friends[u] contains v, u and v
are friends.Friendship is a two-way relationship. Two people are in a friend group as long as there is some path of mutual
friends connecting them.

Request: Implement function:

int numberOfFriendGroups(vector<vector<int>>& friends);


Where friends is the adjacency-list representing the friendship (this list has between 0 and 1000 lists). This function returns
the number of friend groups.

Example:

Given a adjacency-list: [[1], [0, 2], [1], [4], [3], []]

There are 3 friend groups: [0, 1, 2], [3, 4], [5]

Note:
In this exercise, the libraries iostream, string, cstring, climits, utility, vector, list, stack, queue, map, unordered_map,
set, unordered_set, functional, algorithm have been included and namespace std is used. You can write helper functions
and class. Importing other libraries is allowed, but not encouraged.

For example:

Test Result

vector<vector<int>> graph { 3
{1},
{0, 2},
{1},
{4},
{3},
{}
};
cout << numberOfFriendGroups(graph);

Answer: (penalty regime: 0 %)

Reset answer

1 void DFSUtil(int v, bool visited[], vector<vector<int>>& friends)


2 ▼ {
3 visited[v] = true;
4
5 vector<int>::iterator i;
6
7 for (i = friends[v].begin(); i != friends[v].end(); ++i)
8 if (!visited[*i])
9 DFSUtil(*i, visited,friends);
10 }
11 ▼ int numberOfFriendGroups(vector<vector<int>>& friends) {
12 // STUDENT ANSWER
13 bool* visited = new bool[friends.size()];
14 int count = 0;
15 for (size_t v = 0; v < friends.size() ; v++)
16 visited[v] = false;
17

18 ▼ for (size_t v = 0; v < friends.size(); v++) {
19 ▼ if (visited[v] == false) {
20 DFSUtil(v, visited,friends);
21 count += 1;
22 }
23 }
24
https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 25/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS
25 return count;
26 }

Test Expected Got

 vector<vector<int>> graph { 3 3 
\t{1},
\t{0, 2},
\t{1},
\t{4},
\t{3},
\t{}
};
cout << numberOfFriendGroups(graph);

 vector<vector<int>> graph { 0 0 

};
cout << numberOfFriendGroups(graph);

Passed all tests! 

Correct
Marks for this submission: 1.00/1.00.

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 26/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS

Question 8
Correct

Mark 1.00 out of 1.00

Implement function to detect a cyclic in Graph

bool isCyclic();

Graph structure is defined in the initial code.

For example:

Test Result

DirectedGraph g(8); Graph doesn't contain cycle


int edege[][2] = {{0,6}, {1,2}, {1,4}, {1,6}, {3,0}, {3,4}, {5,1}, {7,0}, {7,1}};

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


g.addEdge(edege[i][0], edege[i][1]);

if(g.isCyclic())
cout << "Graph contains cycle";
else
cout << "Graph doesn't contain cycle";

Answer: (penalty regime: 0 %)

Reset answer

1 #include <iostream>
2 #include <vector>
3 #include <list>
4 using namespace std;
5 class DirectedGraph
6▼ {
7 int V;
8 vector<list<int>> adj;
9 public:
10 DirectedGraph(int V)
11 ▼ {
12 this->V = V;
13 adj = vector<list<int>>(V, list<int>());
14 }
15 void addEdge(int v, int w)
16 ▼ {
17 adj[v].push_back(w);
18 }
19 bool isCyclicUtil(int u , bool* visited, bool*reStack)
20 ▼ {
21 if(!visited[u])
22 ▼ {
23 visited[u] = true;
24 reStack[u] = true;
25
26 for(auto x : adj[u])
27 ▼ {
28 if(!visited[x] && isCyclicUtil(x, visited, reStack))
29 return true; 
30 else if(reStack[x])
31 return true;
32 }
33 }
34 reStack[u] = false;
35 return false;
36 }
37 bool isCyclic()
https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 27/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS
37 bool isCyclic()
38 ▼ {
39 // Student answer
40 bool* visited = new bool[this->V], *reStack = new bool[this->V];
41 for(int i = 0 ; i < this->V; ++i)
42 ▼ {
43 visited[i] = false;
44 reStack[i] = false;
45 }
46
47 for(int i = 0 ; i < this->V;++i)
48 ▼ {
49 if(!visited[i] && isCyclicUtil(i,visited, reStack))
50 return true;
51 }
52
53 return false;
54 }
55 };
56

Test Expected Got

 DirectedGraph g(8); Graph doesn't contain Graph doesn't 


int edege[][2] = {{0,6}, {1,2}, {1,4}, {1,6}, {3,0}, {3,4}, cycle contain cycle
{5,1}, {7,0}, {7,1}};

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


\tg.addEdge(edege[i][0], edege[i][1]);

if(g.isCyclic())
\tcout << "Graph contains cycle";
else
\tcout << "Graph doesn't contain cycle";

Passed all tests! 

Correct
Marks for this submission: 1.00/1.00.

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 28/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS

Question 9
Correct

Mark 1.00 out of 1.00

Implement topologicalSort function on a graph. (Ref here)

void topologicalSort();

where Adjacency is a structure to store list of number. Note that, the vertex index starts from 0. To match the given answer, please always
traverse from 0 when performing the sorting.

#include <iostream>
#include <list>
using namespace std;

class Adjacency
{
private:
list<int> adjList;
int size;
public:
Adjacency() {}
Adjacency(int V) {}
void push(int data)
{
adjList.push_back(data);
size++;
}
void print()
{
for (auto const &i : adjList)
cout << " -> " << i;
}
void printArray()
{
for (auto const &i : adjList)
cout << i << " ";
}
int getSize() { return adjList.size(); }
int getElement(int idx)
{
auto it = adjList.begin();
advance(it, idx);
return *it;
}
};

And Graph is a structure to store a graph (see in your answer box). You could write one or more helping functions.

For example:

Test Result

Graph g(6); 5 4 2 3 1 0
g.addEdge(5, 2);

g.addEdge(5, 0);
g.addEdge(4, 0);
g.addEdge(4, 1);
g.addEdge(2, 3);
g.addEdge(3, 1);

g.topologicalSort();

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 29/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS
Answer: (penalty regime: 0 %)

Reset answer

1 ▼ class Graph {
2 int V;
3 Adjacency* adj;
4 public:
5 ▼ Graph(int V){
6 this->V = V;
7 adj = new Adjacency[V];
8 }
9 ▼ void addEdge(int v, int w){
10 adj[v].push(w);
11 }
12
13 //Heling functions
14 void topologicalSortUtil(int v, bool visited[],list<int>& st)
15 ▼ {
16 visited[v] = true;
17
18 for(int i = 0 ; i < this->adj[v].getSize(); ++i)
19 if(!visited[adj[v].getElement(i)])
20 topologicalSortUtil(adj[v].getElement(i), visited,st);
21
22 st.push_back(v);
23 }
24 ▼ void topologicalSort(){
25 //TODO
26 list<int> st;
27 bool* visited = new bool[this->V];
28
29 for(int i = 0 ; i < this-> V; ++i)
30 visited[i] = false;
31
32 for(int i = 0 ; i < this->V; ++i)
33 ▼ {
34 if(!visited[i])
35 topologicalSortUtil(i, visited, st);
36
37 }
38
39 while(!st.empty())
40 ▼ {
41 cout<<st.back()<<" ";
42 st.pop_back();
43 }
44 }
45 };
46

Test Expected Got

 Graph g(6); 5 4 2 3 1 0 5 4 2 3 1 0 
g.addEdge(5, 2);
g.addEdge(5, 0);
g.addEdge(4, 0);
g.addEdge(4, 1); 
g.addEdge(2, 3);
g.addEdge(3, 1);

g.topologicalSort();

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 30/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS
Passed all tests! 

Correct
Marks for this submission: 1.00/1.00.

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 31/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS

Question 10
Correct

Mark 1.00 out of 1.00

Given a graph and a source vertex in the graph, find shortest paths from source to destination vertice in the given graph using
Dijsktra's algorithm.
Following libraries are included: iostream, vector, algorithm, climits, queue

For example:

Test Result

int n = 6; 10
int init[6][6] = {
{0, 10, 20, 0, 0, 0},
{10, 0, 0, 50, 10, 0},
{20, 0, 0, 20, 33, 0},
{0, 50, 20, 0, 20, 2},
{0, 10, 33, 20, 0, 1},
{0, 0, 0, 2, 1, 0} };

int** graph = new int*[n];


for (int i = 0; i < n; ++i) {
graph[i] = init[i];
}

cout << Dijkstra(graph, 0, 1);

Answer: (penalty regime: 0 %)

Reset answer

1 ▼ int Dijkstra(int** graph, int src, int dst) {


2 // TODO: return the length of shortest path from src to dst.
3 int dist[6];
4 bool sptSet[6];
5 for(int i = 0 ; i < 6; ++i)
6 ▼ {
7 dist[i] = INT_MAX;
8 sptSet[i] = false;
9 }
10
11 dist[src] = 0;
12
13 for(int i = 0 ;i < 5; ++i)
14 ▼ {
15 int min = INT_MAX, minIdx;
16 for(int j = 0 ; j < 6; ++j)
17 ▼ {
18 if(!sptSet[j] && dist[j] < min)
19 ▼ {
20 min = dist[j];
21 minIdx = j;
22 }
23 }
24
25 sptSet[minIdx] = true;
26 
27
28 for(int v = 0 ; v < 6; ++v)
29 ▼ {
30 if (!sptSet[v] && graph[minIdx][v] && dist[minIdx] != INT_MAX &&
31 ▼ dist[minIdx] + graph[minIdx][v] < dist[v]) {
32 dist[v] = dist[minIdx] + graph[minIdx][v];
33 }
34 }
https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 32/33
12/9/24, 11:37 AM Graph: Attempt review | BK-LMS
}
35 }
36
37 return dist[dst];
38 }
39
40

Test Expected Got

 int n = 6; 10 10 
int init[6][6] = {
\t{0, 10, 20, 0, 0, 0},
\t{10, 0, 0, 50, 10, 0},
\t{20, 0, 0, 20, 33, 0},
\t{0, 50, 20, 0, 20, 2},
\t{0, 10, 33, 20, 0, 1},
\t{0, 0, 0, 2, 1, 0} };

int** graph = new int*[n];


for (int i = 0; i < n; ++i) {
\tgraph[i] = init[i];
}

cout << Dijkstra(graph, 0, 1);

Passed all tests! 

Correct
Marks for this submission: 1.00/1.00.

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4833769&cmid=470645 33/33

You might also like