SlideShare a Scribd company logo
Implement
Dijkstra’s algorithm using the graph class you implemented in
HW
#5 and
a priority
queue
you have
implemented
earlier this semester
.
Y
ou
r
program will read the graph from a text file like
what we did in
HW
#
5
. You can use
graph.txt from HW
#5
to test your program. Make the header of
the method as Dijsktra(G, v), where v is the starting vertex.
Further, write a method that prints the
shortest path betw
een any two vertices. Example: s
hortestPath(G,
x
,
y
).
Write a main method t
o test
your program.
Instructions:
1.
Y
ou can use C#
or Java programming languages. No other language is allowed or accepted
HW#5 Question
Q1)
(6
0 points)
Implement a
graph ADT by defining a class “Graph” with the operations
below. You
r
ADT should accept either a directed or undirected graph.
isDirect():
tests if the graph is a digraph
. Returns Boolean value.
adjacent(v,
u): tests whether there is an edge from the vertex v to u. returns Boolean value.
n
eighbors(v): returns the list of all vertices that are a destination of an edge from v.
addVertex(v): adds the vertex v to the graph if it is not already in the
graph, otherwise an error
message to be thrown.
removeVertex(v): removes vertex v from the graph, if it is there.
When a vertex is removed, all
edges associated with that vertex should be deleted as well.
addEdge(v,
u): adds the edge that starts from v and
ends at u.
addEdge(v, u, w):
adds the edge t
hat starts from v and ends at u with weight w.
removeEdge(v,
u): remove the edge that connects v and u.
getWeight
(v,
u): returns the weight of the edge from v to u.
setWeight
(v,
u): sets the weight of the edge
from v to u.
isEmpty(): check whether the graph is empty or not.
isComplete(): checks whether the graph is complete or not.
vertices():returns the list of vertices in the graph (i.e
.
, array, vector,..)
edges(): returns the list of edges in the graph.
d
egree(v): return the degree of vertex v.
size(): returns the number of vertices in the graph.
nEdges(): returns the number of edges in the graph.
c
lear(): Reinitializes the graph to be empty, freeing any heap storage.
vertexExists(v): tests whether a verte
x is in the graph or not. Returns true or false.
p
rint(): displays the list of vertices, edges and their weights if the graph is weighted.
Your ADT should contain at least these constructors:
Graph(), creates a graph with zero vertices.
Graph(n), creates
a graph with n vertices.
Graph(n, digraph), where digraph is a Boolean value if true means
a
directed graph.
Q2) (50 points)
Write a main method that r
ead
s
the graph.txt file that contains the information of
directed weighted
graph.
The file is formatted
as the following:
First line is the number of vertices in the graph.
Second line contains the vertices in the graph.
Each
following line contains the edges and the weights. For example: a b 4, means an ed
ge from a to be with
weight = 4.
After
reading the f
ile and creating
the graph perform the following operations in the same order:
•
removeVertex(h)
•
print if the graph is complete or not (i.e., the graph is complete or the graph is not complete)
•
print number of edges in the graph (i.e., number of edges is xx)
•
print if there is a link from a to f (i.e., there is a link from a to f or there is no link from a to f)
•
print the weight of the edge b
à
h (i.e., the weight of the edge from b to h is xx)
•
print the degree of c (i.e., the degree of c is xx)
•
print number of
vertices in the graph (i.e., the graph contains xx vertices)
•
addVertex(k)
•
add(k,a,5)
•
add (g, k, 2)
•
setWeight(a, c, 7)
•
print the graph on the screen. Use the same format in the graph.txt to display information about
the graph on the screen
HW#5 answer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Bond_HW5
{
public class Vertex
{
public string name;
public double distance;
public List edges;
public Vertex()
{
name = "";
edges = new List();
}
public Vertex(string nm)
{
this.name = nm;
edges = new List();
}
}
public class Edge
{
public Vertex target;
public double weight;
public Edge()
{
target = null;
weight = 0;
}
public Edge(Vertex target, double weight)
{
this.target = target;
this.weight = weight;
}
}
public class Graph
{
Vertex[] graph;
int nVertices;
bool isdirected;
public Graph()
{
nVertices = 0;
graph = new Vertex[nVertices];
isdirected = false;
}
public Graph(int n)
{
isdirected = false;
this.nVertices = n;
graph = new Vertex[nVertices];
}
public Graph(int n, bool digraph)
{
isdirected = digraph;
this.nVertices = n;
graph = new Vertex[nVertices];
}
public bool isDirect()
{
if (this.isdirected == true)
{
return true;
}
else
{
return false;
}
}
public bool adjacent(Vertex v, Vertex u)
{
bool vexists = vertexExists(v);
bool uexists = vertexExists(u);
if(vexists && uexists)
{
if (v.edges.Exists(x => x.target.name == u.name))
{
return true;
}
else
{
return false;
}
}
else
return false;
}
public List neighbors(Vertex v)
{
List < Vertex > a = new List();
foreach (Edge e in v.edges.ToArray())
{
a.Add(e.target);
}
return a ;
}
public void addVertex(Vertex v)
{
if(this.vertexExists(v))
{
Console.WriteLine("Error, vertex already exists");
}
else
{
if(graph[0]== null)
{
graph[0] = v;
}
else
{
int i = 1;
while(graph[i]!= null && i < nVertices)
{
i++;
}
if(i>= nVertices)
{
Console.WriteLine("Graph full");
}
else
{
graph[i] = v;
}
}
}
}
public void removeVertex(Vertex v)
{
for (int i = 0; i < nVertices; i++)
{
if (graph[i] != null)
{
if (this.graph[i].name == v.name)
{
graph[i] = null;
}
}
}
}
public void addEdge(Vertex v, Vertex u)
{
bool vexists = vertexExists(v);
bool uexists = vertexExists(u);
if (vexists && uexists)
{
if (isdirected == true)
{
Edge vu = new Edge(u, 0);
v.edges.Add(vu);
}
else
{
Edge vu = new Edge(u, 0);
Edge uv = new Edge(v, 0);
v.edges.Add(vu);
u.edges.Add(uv);
}
}
else if (vexists == true && uexists == false)
{
Console.WriteLine("Error: Vertex 'u' does not exist, please add using the addVertex
Function");
}
else if (vexists == false && uexists == true)
{
Console.WriteLine("Error: Vertex 'v' does not exist, please add using the addVertex
Function");
}
else if (vexists == false && uexists == false)
{
Console.WriteLine("Error: Neither vertex exist, please add using the addVertex
Function");
}
}
public void addEdge(Vertex v, Vertex u, int w)
{
bool vexists = vertexExists(v);
bool uexists = vertexExists(u);
if (vexists && uexists)
{
if (isdirected == true)
{
for (int i = 0; i < nVertices; i++)
{
if (graph[i] != null && graph[i].name == v.name)
{
Edge vu = new Edge(u, w);
graph[i].edges.Add(vu);
}
}
}
else
{
Edge vu = new Edge(u, w);
Edge uv = new Edge(v, w);
v.edges.Add(vu);
u.edges.Add(uv);
}
}
else if (vexists == true && uexists == false)
{
Console.WriteLine("Error: Vertex 'u' does not exist, please add using the addVertex
Function");
}
else if (vexists == false && uexists == true)
{
Console.WriteLine("Error: Vertex 'v' does not exist, please add using the addVertex
Function");
}
else if (vexists == false && uexists == false)
{
Console.WriteLine("Error: Neither vertex exist, please add using the addVertex
Function");
}
}
public double getWeight(Vertex v, Vertex u)
{
Edge temp = new Edge();
for(int i = 0; i x.target.name == u.name);
}
}
return temp.weight;
}
public void setWeight(Vertex v, Vertex u, double w)
{
Edge temp = new Edge();
if (isdirected)
{
for (int i = 0; i < nVertices; i++)
{
if (graph[i] == null || graph[i].name != v.name)
{
continue;
}
else if (graph[i].name == v.name)
{
temp = graph[i].edges.Find(x => x.target.name == u.name);
temp.weight = w;
}
}
}
else
{
for (int i = 0; i < nVertices; i++)
{
if (graph[i] == null || graph[i].name != v.name)
{
continue;
}
else if (graph[i].name == v.name)
{
temp = graph[i].edges.Find(x => x.target.name == u.name);
temp.weight = w;
}
}
for (int j = 0; j < nVertices; j++)
{
if (graph[j] == null || graph[j].name != u.name)
{
continue;
}
else if (graph[j].name == u.name)
{
temp = graph[j].edges.Find(y => y.target.name == u.name);
temp.weight = w;
}
}
}
}
public bool isEmpty()
{
if (nVertices == 0)
return true;
else
return false;
}
public bool isComplete()
{
Edge[] a;
double sum = 0;
double n = graph.Length;
foreach (Vertex x in graph)
{
if (x != null)
{
a = x.edges.ToArray();
sum += a.Length;
}
}
if(sum < ((n*(n-1)/2)))
{
return false;
}
else
return true;
}
public Vertex[] vertices()
{
return graph;
}
public string edges()
{
string elist = "";
Edge[] arr;
foreach (Vertex x in graph)
{
if (x != null)
{
arr = x.edges.ToArray();
for (int i = 0; i < arr.Length; i++)
{
if (arr[i].target != null)
{
elist = elist+x.name + arr[i].target.name + "("+arr[i].weight+")";
elist += "|";
}
}
}
}
return elist;
}
public int degree(Vertex V)
{
if (isdirected)
{
int counter = 0;
for (int i = 0; i < nVertices; i++)
{
if (graph[i] != null && graph[i].name == V.name)
{
foreach (Edge e in graph[i].edges)
{
counter++;
}
}
}
return counter;
}
else
{
int counter = 0;
for (int i = 0; i < nVertices; i++)
{
if (graph[i] != null && graph[i].name == V.name)
{
foreach (Edge e in graph[i].edges)
{
counter++;
}
}
}
return counter;
}
}
public double size()
{
return graph.Length;
}
public double Nedges()
{
Edge[] a;
double sum = 0;
double n = graph.Length;
foreach (Vertex x in graph)
{
if (x != null)
{
a = x.edges.ToArray();
sum += a.Length;
}
}
if (isdirected)
{
return sum;
}
else
{
return sum / 2;
}
}
public void clear()
{
for (int i = 0; i < nVertices; i++)
{
graph[i] = null;
}
}
public bool vertexExists(Vertex v)
{
for(int i =0; i< nVertices; i++)
{
if (graph[i] != null)
{
if (graph[i].name == v.name)
return true;
}
else
{
continue;
}
}
return false;
}
public void print()
{
Console.WriteLine("Vertices: ");
foreach (Vertex v in graph)
{
if (v != null)
{
Console.WriteLine("name: " + v.name);
}
}
Console.WriteLine("Edges: ");
Console.WriteLine(edges());
}
}
class Program
{
static void Main(string[] args)
{
/*
Graph a = new Graph(10, false);
Vertex b = new Vertex();
Vertex c = new Vertex();
c.name = "c";
b.name = "b";
a.addVertex(b);
a.addVertex(c);
a.addEdge(b, c, 10);
a.print();*/
// INput from txt file
StreamReader Reader = new StreamReader("graph.txt");
int numvert;
string[] vertchars;
List edgecreator = new List();
numvert = int.Parse(Reader.ReadLine());
vertchars = new string[numvert];
Graph myGraph = new Graph(numvert, true);
string thechars = Reader.ReadLine();
vertchars = thechars.Split(' ');
foreach(string character in vertchars)
{
Vertex adder = new Vertex(character);
myGraph.addVertex(adder);
}
string edgeReader;
while((edgeReader = Reader.ReadLine())!= null)
{
edgecreator.Add(edgeReader);
}
string[] b = edgecreator.ToArray();
foreach(string sent in b)
{
string[] splitter = sent.Split(' ');
Vertex a = new Vertex(splitter[0]);
Vertex c = new Vertex(splitter[1]);
myGraph.addEdge(a, c, int.Parse(splitter[2]));
}
Vertex tester = new Vertex();
Vertex tester2 = new Vertex();
//print the weight of edge b to h
tester.name = "b";
tester2.name = "h";
double theWeight = myGraph.getWeight(tester, tester2);
Console.WriteLine("The weight from b->h is {0}", theWeight);
//remove vertex h
myGraph.removeVertex(tester2);
//print whether or not the graph is complete
bool comp = myGraph.isComplete();
if(comp)
{
Console.WriteLine("the graph is complete");
}
else
{
Console.WriteLine("the graph is not complete");
}
//print whethether there is a link from a to f
tester = new Vertex("a");
tester2 = new Vertex("f");
comp = myGraph.adjacent(tester, tester2);
if (comp)
{
Console.WriteLine("there is a link from a to f");
}
else
{
Console.WriteLine("there is not a link from a to f");
}
//print the degree of c
Vertex tester3 = new Vertex("c");
Console.WriteLine("the out degree of c is {0}", myGraph.degree(tester3));
//print number of vertices
Console.WriteLine("The number of vertices is {0}", myGraph.vertices().Length);
//add vertex k
tester2 = new Vertex("k");
myGraph.addVertex(tester2);
//add edge k,a,5
myGraph.addEdge(tester2, tester);
//add edge g k 2
Vertex tester4 = new Vertex("g");
myGraph.addEdge(tester4, tester2);
//set weight a,c,7
myGraph.setWeight(tester, tester3, 7);
//print graph
myGraph.print();
}
}
}
Solution
Please Find the

More Related Content

Similar to ImplementDijkstra’s algorithm using the graph class you implemente.pdf (20)

PDF
Create a java project that - Draw a circle with three random init.pdf
arihantmobileselepun
 
DOC
Lesson 3
Vinnu Vinay
 
PPT
Graphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.ppt
babanazar7204
 
PPTX
Data Structures and Agorithm: DS 21 Graph Theory.pptx
RashidFaridChishti
 
PPT
CS 354 Transformation, Clipping, and Culling
Mark Kilgard
 
PPT
Unit27_MinimumSpanningTree.ppt data structure programming
Arjunkrish9
 
PPT
Unit26 shortest pathalgorithm
meisamstar
 
PPT
lecture 17
sajinsc
 
PDF
Artificial Intelligence Practical Manual.pdf
priyanshi25121980
 
PDF
Computer Graphics in Java and Scala - Part 1
Philip Schwarz
 
PDF
Lec 9 05_sept [compatibility mode]
Palak Sanghani
 
PDF
Matlab plotting
pramodkumar1804
 
DOCX
Introduction to r
Golden Julie Jesus
 
PDF
Lecture13
vaishali_singh
 
DOCX
Write a program that reads a graph from a file anil determines whethe.docx
ajoy21
 
PDF
Gremlin's Graph Traversal Machinery
Marko Rodriguez
 
PDF
DataStax | Graph Computing with Apache TinkerPop (Marko Rodriguez) | Cassandr...
DataStax
 
PPTX
Beginning direct3d gameprogrammingmath03_vectors_20160328_jintaeks
JinTaek Seo
 
PDF
Hive Functions Cheat Sheet
Hortonworks
 
PPT
ch03g-graphics.ppt
Mahyuddin8
 
Create a java project that - Draw a circle with three random init.pdf
arihantmobileselepun
 
Lesson 3
Vinnu Vinay
 
Graphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.ppt
babanazar7204
 
Data Structures and Agorithm: DS 21 Graph Theory.pptx
RashidFaridChishti
 
CS 354 Transformation, Clipping, and Culling
Mark Kilgard
 
Unit27_MinimumSpanningTree.ppt data structure programming
Arjunkrish9
 
Unit26 shortest pathalgorithm
meisamstar
 
lecture 17
sajinsc
 
Artificial Intelligence Practical Manual.pdf
priyanshi25121980
 
Computer Graphics in Java and Scala - Part 1
Philip Schwarz
 
Lec 9 05_sept [compatibility mode]
Palak Sanghani
 
Matlab plotting
pramodkumar1804
 
Introduction to r
Golden Julie Jesus
 
Lecture13
vaishali_singh
 
Write a program that reads a graph from a file anil determines whethe.docx
ajoy21
 
Gremlin's Graph Traversal Machinery
Marko Rodriguez
 
DataStax | Graph Computing with Apache TinkerPop (Marko Rodriguez) | Cassandr...
DataStax
 
Beginning direct3d gameprogrammingmath03_vectors_20160328_jintaeks
JinTaek Seo
 
Hive Functions Cheat Sheet
Hortonworks
 
ch03g-graphics.ppt
Mahyuddin8
 

More from gopalk44 (20)

PDF
My protease appears to affect bacteria, but not my own cells. What t.pdf
gopalk44
 
PDF
Name the phases in interphase, and describe what happens during those.pdf
gopalk44
 
PDF
Look for at least four definitions of accounting (from four differen.pdf
gopalk44
 
PDF
Match the word or phrase with the best description of it. ;An express.pdf
gopalk44
 
PDF
JAVAThe mean of a list of numbers is its arithmetic average. The .pdf
gopalk44
 
PDF
Know and understand the contributions of Hooke, van Leeuwenhoek, Cohn.pdf
gopalk44
 
PDF
Illegal numbers.a. Complete the method find which accepts a collec.pdf
gopalk44
 
PDF
how many chromosomes will be found in each cell at the end of anapha.pdf
gopalk44
 
PDF
how are the technological approaches of cloning and IPSCs similar to.pdf
gopalk44
 
PDF
HELP! Thought I can figure this one out but got it wrong. I have one.pdf
gopalk44
 
PDF
From a recent statistical analysis for the last five years, on an av.pdf
gopalk44
 
PDF
Find asymptotic upperlower bounds. Find asymptotic upperlower boun.pdf
gopalk44
 
PDF
Explain how a wireless device can help an organization perform busin.pdf
gopalk44
 
PDF
Exam scores were normal in BIO 200. Jasons exam score was one stan.pdf
gopalk44
 
PDF
Discuss the various types of business crimes, a business liability f.pdf
gopalk44
 
PDF
Describe the different types of ribs. Which ribs are considered “fal.pdf
gopalk44
 
PDF
Circle the best answer to the following questions. From the Bohr mod.pdf
gopalk44
 
PDF
C++ ProgramN-number queue rotations.[16] Write methods void Que.pdf
gopalk44
 
PDF
Below are two possible tree topologies. How many clades are different.pdf
gopalk44
 
PDF
WriteBelow are a list of descriptions that apply to either post s.pdf
gopalk44
 
My protease appears to affect bacteria, but not my own cells. What t.pdf
gopalk44
 
Name the phases in interphase, and describe what happens during those.pdf
gopalk44
 
Look for at least four definitions of accounting (from four differen.pdf
gopalk44
 
Match the word or phrase with the best description of it. ;An express.pdf
gopalk44
 
JAVAThe mean of a list of numbers is its arithmetic average. The .pdf
gopalk44
 
Know and understand the contributions of Hooke, van Leeuwenhoek, Cohn.pdf
gopalk44
 
Illegal numbers.a. Complete the method find which accepts a collec.pdf
gopalk44
 
how many chromosomes will be found in each cell at the end of anapha.pdf
gopalk44
 
how are the technological approaches of cloning and IPSCs similar to.pdf
gopalk44
 
HELP! Thought I can figure this one out but got it wrong. I have one.pdf
gopalk44
 
From a recent statistical analysis for the last five years, on an av.pdf
gopalk44
 
Find asymptotic upperlower bounds. Find asymptotic upperlower boun.pdf
gopalk44
 
Explain how a wireless device can help an organization perform busin.pdf
gopalk44
 
Exam scores were normal in BIO 200. Jasons exam score was one stan.pdf
gopalk44
 
Discuss the various types of business crimes, a business liability f.pdf
gopalk44
 
Describe the different types of ribs. Which ribs are considered “fal.pdf
gopalk44
 
Circle the best answer to the following questions. From the Bohr mod.pdf
gopalk44
 
C++ ProgramN-number queue rotations.[16] Write methods void Que.pdf
gopalk44
 
Below are two possible tree topologies. How many clades are different.pdf
gopalk44
 
WriteBelow are a list of descriptions that apply to either post s.pdf
gopalk44
 
Ad

Recently uploaded (20)

PPTX
ESP 10 Edukasyon sa Pagpapakatao PowerPoint Lessons Quarter 1.pptx
Sir J.
 
PPTX
How Physics Enhances Our Quality of Life.pptx
AngeliqueTolentinoDe
 
PPTX
Comparing Translational and Rotational Motion.pptx
AngeliqueTolentinoDe
 
PPTX
Connecting Linear and Angular Quantities in Human Movement.pptx
AngeliqueTolentinoDe
 
PDF
Gladiolous Cultivation practices by AKL.pdf
kushallamichhame
 
PPTX
The Gift of the Magi by O Henry-A Story of True Love, Sacrifice, and Selfless...
Beena E S
 
PDF
COM and NET Component Services 1st Edition Juval Löwy
kboqcyuw976
 
DOCX
MUSIC AND ARTS 5 DLL MATATAG LESSON EXEMPLAR QUARTER 1_Q1_W1.docx
DianaValiente5
 
PDF
Quiz Night Live May 2025 - Intra Pragya Online General Quiz
Pragya - UEM Kolkata Quiz Club
 
PDF
Lesson 1 : Science and the Art of Geography Ecosystem
marvinnbustamante1
 
PPTX
Urban Hierarchy and Service Provisions.pptx
Islamic University of Bangladesh
 
PDF
The Power of Compound Interest (Stanford Initiative for Financial Decision-Ma...
Stanford IFDM
 
PPTX
Ward Management: Patient Care, Personnel, Equipment, and Environment.pptx
PRADEEP ABOTHU
 
PPTX
Lesson 1 Cell (Structures, Functions, and Theory).pptx
marvinnbustamante1
 
PPTX
How to Create & Manage Stages in Odoo 18 Helpdesk
Celine George
 
PDF
CAD25 Gbadago and Fafa Presentation Revised-Aston Business School, UK.pdf
Kweku Zurek
 
PDF
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
trjnesjnqg7801
 
PDF
Learning Styles Inventory for Senior High School Students
Thelma Villaflores
 
PDF
Nanotechnology and Functional Foods Effective Delivery of Bioactive Ingredien...
rmswlwcxai8321
 
PDF
TechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.06.25.pdf
TechSoup
 
ESP 10 Edukasyon sa Pagpapakatao PowerPoint Lessons Quarter 1.pptx
Sir J.
 
How Physics Enhances Our Quality of Life.pptx
AngeliqueTolentinoDe
 
Comparing Translational and Rotational Motion.pptx
AngeliqueTolentinoDe
 
Connecting Linear and Angular Quantities in Human Movement.pptx
AngeliqueTolentinoDe
 
Gladiolous Cultivation practices by AKL.pdf
kushallamichhame
 
The Gift of the Magi by O Henry-A Story of True Love, Sacrifice, and Selfless...
Beena E S
 
COM and NET Component Services 1st Edition Juval Löwy
kboqcyuw976
 
MUSIC AND ARTS 5 DLL MATATAG LESSON EXEMPLAR QUARTER 1_Q1_W1.docx
DianaValiente5
 
Quiz Night Live May 2025 - Intra Pragya Online General Quiz
Pragya - UEM Kolkata Quiz Club
 
Lesson 1 : Science and the Art of Geography Ecosystem
marvinnbustamante1
 
Urban Hierarchy and Service Provisions.pptx
Islamic University of Bangladesh
 
The Power of Compound Interest (Stanford Initiative for Financial Decision-Ma...
Stanford IFDM
 
Ward Management: Patient Care, Personnel, Equipment, and Environment.pptx
PRADEEP ABOTHU
 
Lesson 1 Cell (Structures, Functions, and Theory).pptx
marvinnbustamante1
 
How to Create & Manage Stages in Odoo 18 Helpdesk
Celine George
 
CAD25 Gbadago and Fafa Presentation Revised-Aston Business School, UK.pdf
Kweku Zurek
 
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
trjnesjnqg7801
 
Learning Styles Inventory for Senior High School Students
Thelma Villaflores
 
Nanotechnology and Functional Foods Effective Delivery of Bioactive Ingredien...
rmswlwcxai8321
 
TechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.06.25.pdf
TechSoup
 
Ad

ImplementDijkstra’s algorithm using the graph class you implemente.pdf

  • 1. Implement Dijkstra’s algorithm using the graph class you implemented in HW #5 and a priority queue you have implemented earlier this semester . Y ou r program will read the graph from a text file like what we did in HW # 5 . You can use graph.txt from HW #5 to test your program. Make the header of the method as Dijsktra(G, v), where v is the starting vertex. Further, write a method that prints the shortest path betw een any two vertices. Example: s hortestPath(G, x , y ). Write a main method t o test your program. Instructions:
  • 2. 1. Y ou can use C# or Java programming languages. No other language is allowed or accepted HW#5 Question Q1) (6 0 points) Implement a graph ADT by defining a class “Graph” with the operations below. You r ADT should accept either a directed or undirected graph. isDirect(): tests if the graph is a digraph . Returns Boolean value. adjacent(v, u): tests whether there is an edge from the vertex v to u. returns Boolean value. n eighbors(v): returns the list of all vertices that are a destination of an edge from v. addVertex(v): adds the vertex v to the graph if it is not already in the graph, otherwise an error message to be thrown. removeVertex(v): removes vertex v from the graph, if it is there. When a vertex is removed, all edges associated with that vertex should be deleted as well. addEdge(v, u): adds the edge that starts from v and ends at u. addEdge(v, u, w): adds the edge t hat starts from v and ends at u with weight w. removeEdge(v, u): remove the edge that connects v and u. getWeight (v,
  • 3. u): returns the weight of the edge from v to u. setWeight (v, u): sets the weight of the edge from v to u. isEmpty(): check whether the graph is empty or not. isComplete(): checks whether the graph is complete or not. vertices():returns the list of vertices in the graph (i.e . , array, vector,..) edges(): returns the list of edges in the graph. d egree(v): return the degree of vertex v. size(): returns the number of vertices in the graph. nEdges(): returns the number of edges in the graph. c lear(): Reinitializes the graph to be empty, freeing any heap storage. vertexExists(v): tests whether a verte x is in the graph or not. Returns true or false. p rint(): displays the list of vertices, edges and their weights if the graph is weighted. Your ADT should contain at least these constructors: Graph(), creates a graph with zero vertices. Graph(n), creates a graph with n vertices. Graph(n, digraph), where digraph is a Boolean value if true means a directed graph. Q2) (50 points) Write a main method that r ead s the graph.txt file that contains the information of directed weighted graph. The file is formatted
  • 4. as the following: First line is the number of vertices in the graph. Second line contains the vertices in the graph. Each following line contains the edges and the weights. For example: a b 4, means an ed ge from a to be with weight = 4. After reading the f ile and creating the graph perform the following operations in the same order: • removeVertex(h) • print if the graph is complete or not (i.e., the graph is complete or the graph is not complete) • print number of edges in the graph (i.e., number of edges is xx) • print if there is a link from a to f (i.e., there is a link from a to f or there is no link from a to f) • print the weight of the edge b à h (i.e., the weight of the edge from b to h is xx) • print the degree of c (i.e., the degree of c is xx) • print number of vertices in the graph (i.e., the graph contains xx vertices) • addVertex(k) • add(k,a,5) • add (g, k, 2) • setWeight(a, c, 7)
  • 5. • print the graph on the screen. Use the same format in the graph.txt to display information about the graph on the screen HW#5 answer using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace Bond_HW5 { public class Vertex { public string name; public double distance; public List edges; public Vertex() { name = ""; edges = new List(); } public Vertex(string nm) { this.name = nm; edges = new List(); } } public class Edge { public Vertex target; public double weight; public Edge() {
  • 6. target = null; weight = 0; } public Edge(Vertex target, double weight) { this.target = target; this.weight = weight; } } public class Graph { Vertex[] graph; int nVertices; bool isdirected; public Graph() { nVertices = 0; graph = new Vertex[nVertices]; isdirected = false; } public Graph(int n) { isdirected = false; this.nVertices = n; graph = new Vertex[nVertices]; } public Graph(int n, bool digraph) { isdirected = digraph; this.nVertices = n; graph = new Vertex[nVertices]; } public bool isDirect() {
  • 7. if (this.isdirected == true) { return true; } else { return false; } } public bool adjacent(Vertex v, Vertex u) { bool vexists = vertexExists(v); bool uexists = vertexExists(u); if(vexists && uexists) { if (v.edges.Exists(x => x.target.name == u.name)) { return true; } else { return false; } } else return false; } public List neighbors(Vertex v) { List < Vertex > a = new List(); foreach (Edge e in v.edges.ToArray()) { a.Add(e.target); }
  • 8. return a ; } public void addVertex(Vertex v) { if(this.vertexExists(v)) { Console.WriteLine("Error, vertex already exists"); } else { if(graph[0]== null) { graph[0] = v; } else { int i = 1; while(graph[i]!= null && i < nVertices) { i++; } if(i>= nVertices) { Console.WriteLine("Graph full"); } else { graph[i] = v; } } } } public void removeVertex(Vertex v) { for (int i = 0; i < nVertices; i++)
  • 9. { if (graph[i] != null) { if (this.graph[i].name == v.name) { graph[i] = null; } } } } public void addEdge(Vertex v, Vertex u) { bool vexists = vertexExists(v); bool uexists = vertexExists(u); if (vexists && uexists) { if (isdirected == true) { Edge vu = new Edge(u, 0); v.edges.Add(vu); } else { Edge vu = new Edge(u, 0); Edge uv = new Edge(v, 0); v.edges.Add(vu); u.edges.Add(uv); } } else if (vexists == true && uexists == false) { Console.WriteLine("Error: Vertex 'u' does not exist, please add using the addVertex Function"); }
  • 10. else if (vexists == false && uexists == true) { Console.WriteLine("Error: Vertex 'v' does not exist, please add using the addVertex Function"); } else if (vexists == false && uexists == false) { Console.WriteLine("Error: Neither vertex exist, please add using the addVertex Function"); } } public void addEdge(Vertex v, Vertex u, int w) { bool vexists = vertexExists(v); bool uexists = vertexExists(u); if (vexists && uexists) { if (isdirected == true) { for (int i = 0; i < nVertices; i++) { if (graph[i] != null && graph[i].name == v.name) { Edge vu = new Edge(u, w); graph[i].edges.Add(vu); } } } else { Edge vu = new Edge(u, w); Edge uv = new Edge(v, w); v.edges.Add(vu); u.edges.Add(uv); }
  • 11. } else if (vexists == true && uexists == false) { Console.WriteLine("Error: Vertex 'u' does not exist, please add using the addVertex Function"); } else if (vexists == false && uexists == true) { Console.WriteLine("Error: Vertex 'v' does not exist, please add using the addVertex Function"); } else if (vexists == false && uexists == false) { Console.WriteLine("Error: Neither vertex exist, please add using the addVertex Function"); } } public double getWeight(Vertex v, Vertex u) { Edge temp = new Edge(); for(int i = 0; i x.target.name == u.name); } } return temp.weight; } public void setWeight(Vertex v, Vertex u, double w) { Edge temp = new Edge(); if (isdirected) { for (int i = 0; i < nVertices; i++) { if (graph[i] == null || graph[i].name != v.name) { continue; }
  • 12. else if (graph[i].name == v.name) { temp = graph[i].edges.Find(x => x.target.name == u.name); temp.weight = w; } } } else { for (int i = 0; i < nVertices; i++) { if (graph[i] == null || graph[i].name != v.name) { continue; } else if (graph[i].name == v.name) { temp = graph[i].edges.Find(x => x.target.name == u.name); temp.weight = w; } } for (int j = 0; j < nVertices; j++) { if (graph[j] == null || graph[j].name != u.name) { continue; } else if (graph[j].name == u.name) { temp = graph[j].edges.Find(y => y.target.name == u.name); temp.weight = w; } } } } public bool isEmpty()
  • 13. { if (nVertices == 0) return true; else return false; } public bool isComplete() { Edge[] a; double sum = 0; double n = graph.Length; foreach (Vertex x in graph) { if (x != null) { a = x.edges.ToArray(); sum += a.Length; } } if(sum < ((n*(n-1)/2))) { return false; } else return true; } public Vertex[] vertices() { return graph; } public string edges() { string elist = ""; Edge[] arr; foreach (Vertex x in graph) {
  • 14. if (x != null) { arr = x.edges.ToArray(); for (int i = 0; i < arr.Length; i++) { if (arr[i].target != null) { elist = elist+x.name + arr[i].target.name + "("+arr[i].weight+")"; elist += "|"; } } } } return elist; } public int degree(Vertex V) { if (isdirected) { int counter = 0; for (int i = 0; i < nVertices; i++) { if (graph[i] != null && graph[i].name == V.name) { foreach (Edge e in graph[i].edges) { counter++; } } } return counter; } else { int counter = 0; for (int i = 0; i < nVertices; i++)
  • 15. { if (graph[i] != null && graph[i].name == V.name) { foreach (Edge e in graph[i].edges) { counter++; } } } return counter; } } public double size() { return graph.Length; } public double Nedges() { Edge[] a; double sum = 0; double n = graph.Length; foreach (Vertex x in graph) { if (x != null) { a = x.edges.ToArray(); sum += a.Length; } } if (isdirected) { return sum; } else { return sum / 2;
  • 16. } } public void clear() { for (int i = 0; i < nVertices; i++) { graph[i] = null; } } public bool vertexExists(Vertex v) { for(int i =0; i< nVertices; i++) { if (graph[i] != null) { if (graph[i].name == v.name) return true; } else { continue; } } return false; } public void print() { Console.WriteLine("Vertices: "); foreach (Vertex v in graph) { if (v != null) { Console.WriteLine("name: " + v.name); } } Console.WriteLine("Edges: ");
  • 17. Console.WriteLine(edges()); } } class Program { static void Main(string[] args) { /* Graph a = new Graph(10, false); Vertex b = new Vertex(); Vertex c = new Vertex(); c.name = "c"; b.name = "b"; a.addVertex(b); a.addVertex(c); a.addEdge(b, c, 10); a.print();*/ // INput from txt file StreamReader Reader = new StreamReader("graph.txt"); int numvert; string[] vertchars; List edgecreator = new List(); numvert = int.Parse(Reader.ReadLine()); vertchars = new string[numvert]; Graph myGraph = new Graph(numvert, true); string thechars = Reader.ReadLine(); vertchars = thechars.Split(' '); foreach(string character in vertchars) { Vertex adder = new Vertex(character); myGraph.addVertex(adder); } string edgeReader; while((edgeReader = Reader.ReadLine())!= null) { edgecreator.Add(edgeReader);
  • 18. } string[] b = edgecreator.ToArray(); foreach(string sent in b) { string[] splitter = sent.Split(' '); Vertex a = new Vertex(splitter[0]); Vertex c = new Vertex(splitter[1]); myGraph.addEdge(a, c, int.Parse(splitter[2])); } Vertex tester = new Vertex(); Vertex tester2 = new Vertex(); //print the weight of edge b to h tester.name = "b"; tester2.name = "h"; double theWeight = myGraph.getWeight(tester, tester2); Console.WriteLine("The weight from b->h is {0}", theWeight); //remove vertex h myGraph.removeVertex(tester2); //print whether or not the graph is complete bool comp = myGraph.isComplete(); if(comp) { Console.WriteLine("the graph is complete"); } else { Console.WriteLine("the graph is not complete"); } //print whethether there is a link from a to f tester = new Vertex("a"); tester2 = new Vertex("f"); comp = myGraph.adjacent(tester, tester2); if (comp) { Console.WriteLine("there is a link from a to f"); }
  • 19. else { Console.WriteLine("there is not a link from a to f"); } //print the degree of c Vertex tester3 = new Vertex("c"); Console.WriteLine("the out degree of c is {0}", myGraph.degree(tester3)); //print number of vertices Console.WriteLine("The number of vertices is {0}", myGraph.vertices().Length); //add vertex k tester2 = new Vertex("k"); myGraph.addVertex(tester2); //add edge k,a,5 myGraph.addEdge(tester2, tester); //add edge g k 2 Vertex tester4 = new Vertex("g"); myGraph.addEdge(tester4, tester2); //set weight a,c,7 myGraph.setWeight(tester, tester3, 7); //print graph myGraph.print(); } } } Solution Please Find the