SlideShare a Scribd company logo
1 of 19
Download to read offline
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

CS 354 Transformation, Clipping, and Culling
CS 354 Transformation, Clipping, and CullingCS 354 Transformation, Clipping, and Culling
CS 354 Transformation, Clipping, and CullingMark Kilgard
 
Unit26 shortest pathalgorithm
Unit26 shortest pathalgorithmUnit26 shortest pathalgorithm
Unit26 shortest pathalgorithmmeisamstar
 
lecture 17
lecture 17lecture 17
lecture 17sajinsc
 
Computer Graphics in Java and Scala - Part 1
Computer Graphics in Java and Scala - Part 1Computer Graphics in Java and Scala - Part 1
Computer Graphics in Java and Scala - Part 1Philip Schwarz
 
Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Palak Sanghani
 
Write a program that reads a graph from a file anil determines whethe.docx
 Write a program that reads a graph from a file anil determines whethe.docx Write a program that reads a graph from a file anil determines whethe.docx
Write a program that reads a graph from a file anil determines whethe.docxajoy21
 
Gremlin's Graph Traversal Machinery
Gremlin's Graph Traversal MachineryGremlin's Graph Traversal Machinery
Gremlin's Graph Traversal MachineryMarko Rodriguez
 
DataStax | Graph Computing with Apache TinkerPop (Marko Rodriguez) | Cassandr...
DataStax | Graph Computing with Apache TinkerPop (Marko Rodriguez) | Cassandr...DataStax | Graph Computing with Apache TinkerPop (Marko Rodriguez) | Cassandr...
DataStax | Graph Computing with Apache TinkerPop (Marko Rodriguez) | Cassandr...DataStax
 
Beginning direct3d gameprogrammingmath03_vectors_20160328_jintaeks
Beginning direct3d gameprogrammingmath03_vectors_20160328_jintaeksBeginning direct3d gameprogrammingmath03_vectors_20160328_jintaeks
Beginning direct3d gameprogrammingmath03_vectors_20160328_jintaeksJinTaek Seo
 
Hive Functions Cheat Sheet
Hive Functions Cheat SheetHive Functions Cheat Sheet
Hive Functions Cheat SheetHortonworks
 
ch03g-graphics.ppt
ch03g-graphics.pptch03g-graphics.ppt
ch03g-graphics.pptMahyuddin8
 
Numerical analysis
Numerical analysisNumerical analysis
Numerical analysisVishal Singh
 

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

Lesson 3
Lesson 3Lesson 3
Lesson 3
 
CS 354 Transformation, Clipping, and Culling
CS 354 Transformation, Clipping, and CullingCS 354 Transformation, Clipping, and Culling
CS 354 Transformation, Clipping, and Culling
 
Unit26 shortest pathalgorithm
Unit26 shortest pathalgorithmUnit26 shortest pathalgorithm
Unit26 shortest pathalgorithm
 
lecture 17
lecture 17lecture 17
lecture 17
 
Computer Graphics in Java and Scala - Part 1
Computer Graphics in Java and Scala - Part 1Computer Graphics in Java and Scala - Part 1
Computer Graphics in Java and Scala - Part 1
 
Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]
 
Matlab plotting
Matlab plottingMatlab plotting
Matlab plotting
 
Introduction to r
Introduction to rIntroduction to r
Introduction to r
 
Lecture13
Lecture13Lecture13
Lecture13
 
Write a program that reads a graph from a file anil determines whethe.docx
 Write a program that reads a graph from a file anil determines whethe.docx Write a program that reads a graph from a file anil determines whethe.docx
Write a program that reads a graph from a file anil determines whethe.docx
 
Gremlin's Graph Traversal Machinery
Gremlin's Graph Traversal MachineryGremlin's Graph Traversal Machinery
Gremlin's Graph Traversal Machinery
 
DataStax | Graph Computing with Apache TinkerPop (Marko Rodriguez) | Cassandr...
DataStax | Graph Computing with Apache TinkerPop (Marko Rodriguez) | Cassandr...DataStax | Graph Computing with Apache TinkerPop (Marko Rodriguez) | Cassandr...
DataStax | Graph Computing with Apache TinkerPop (Marko Rodriguez) | Cassandr...
 
Beginning direct3d gameprogrammingmath03_vectors_20160328_jintaeks
Beginning direct3d gameprogrammingmath03_vectors_20160328_jintaeksBeginning direct3d gameprogrammingmath03_vectors_20160328_jintaeks
Beginning direct3d gameprogrammingmath03_vectors_20160328_jintaeks
 
Hive Functions Cheat Sheet
Hive Functions Cheat SheetHive Functions Cheat Sheet
Hive Functions Cheat Sheet
 
ch03g-graphics.ppt
ch03g-graphics.pptch03g-graphics.ppt
ch03g-graphics.ppt
 
Numerical analysis
Numerical analysisNumerical analysis
Numerical analysis
 
13slide graphics
13slide graphics13slide graphics
13slide graphics
 
Graphs
GraphsGraphs
Graphs
 
Struct examples
Struct examplesStruct examples
Struct examples
 
Computer Science Assignment Help
Computer Science Assignment Help Computer Science Assignment Help
Computer Science Assignment Help
 

More from gopalk44

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

More from gopalk44 (20)

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

Recently uploaded

CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 

Recently uploaded (20)

CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 

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