Question

In this exercise you're going to implement a graph class using an adjacency matrix of size...

In this exercise you're going to implement a graph class using an adjacency matrix of size 26x26. This allows up to 26 vertices, which will be denoted by the uppercase letters A .. Z. Initially a graph is empty, and then vertices and edges are added. Edges are directed, and have weights. Example: (A, B, 100) denotes an edge from A to B with weight 100; there is no edge from B to A unless one is explicitly added.

A main program is provided in "main.cpp" for testing. Your assignment is to implement "graph.h" and define a graph class; you must create the class from scratch, do not use templates. Inside your class, the adjacency matrix should be defined in the private section as follows:

int matrix[26][26];

Row 0 of the matrix denotes the edges starting at vertex A; row 1 denotes the edges starting at vertex B, etc. Similarly, column 0 denotes the edges ending at vertex A, column 1 denotes the edges ending at vertex B, etc. Example: the edge (A, B, 100) is represented by matrix[0][1] == 100. Since edge weights will be 0 or positive, the graph constructor should initialize the matrix to -1 (denoting no edge).

Add the following functions to your graph class, exactly as defined here:

// add the vertex v to the graph

void addvertex(char v);

// add the edge (from, to, weight) to the graph, but only if

// the vertices from and to have been added to the graph

void addedge(char from, char to, int weight);

// return the weight on the edge (from, to, ?); return -1 if no edge exists

int getweight(char from, char to);

// returns the vertices in the graph, in order A .. Z

vector<char> vertices();

// returns the neighbors of a vertex v, i.e. all vertices you can reach from

// v by traversing one edge.

vector<char> neighbors(char v);

Since a graph is initially empty, you'll need another data structure to keep track of vertices as they are added to the graph. You can use a vector, or a boolean array, or whatever you prefer. Be sure to initialize this data structure (if necessary) in the constructor.

/*graph.h*/ is the file to work on

#pragma once

#include <iostream>
#include <vector>
#include <string>

using namespace std;

class graph
{
//
// TODO:
//

};

/*main.cpp*/ is a read only file

#include <iostream>
#include <vector>
#include <string>

#include "graph.h"

using namespace std;

void outputGraph(graph& g)
{
vector<char> vertices = g.vertices();

cout << "**Vertices: ";

for (char c : vertices)
{
cout << c << " ";
}

cout << endl;

cout << "**Edges: ";

for (char v : vertices)
{
vector<char> neighbors = g.neighbors(v);

for (char n : neighbors)
{
int weight = g.getweight(v, n);
cout << "(" << v << "," << n << "," << weight << ") ";
}
}

cout << endl;
}


int main()
{
graph g;
string input;

//
// Input vertices as single uppercase letters: A B C ...
//
cout << "Enter vertices as single letters, separated by spaces, end with #> ";
cin >> input;

while (input != "#")
{
char vertex = input[0];

g.addvertex(vertex);

cin >> input;
}

cout << endl;

//
// Now input edges:
//
string src, dest, weight;

cout << "Enter edge as LETTER LETTER WEIGHT, or #> ";
cin >> src;

while (src != "#")
{
cin >> dest;
cin >> weight;

//cout << src << ", " << dest << ", " << weight << endl;

g.addedge(src[0], dest[0], stoi(weight));

cout << "Enter edge as LETTER LETTER WEIGHT, or #> ";
cin >> src;
}

cout << endl;

//
// Now dump the graph to output stream:
//
outputGraph(g);

//
// done:
//
return 0;
}

Homework Answers

Answer #1

// graph.h

#pragma once

#include <iostream>
#include <vector>
#include <string>

using namespace std;

class graph
{
private :
   bool vertex[26];
   int matrix[26][26];

public:
   graph();
   // add the vertex v to the graph
   void addvertex(char v);
   // add the edge (from, to, weight) to the graph, but only if
   // the vertices from and to have been added to the graph
   void addedge(char from, char to, int weight);
   // return the weight on the edge (from, to, ?); return -1 if no edge exists
   int getweight(char from, char to);
   // returns the vertices in the graph, in order A .. Z
   vector<char> vertices();
   // returns the neighbors of a vertex v, i.e. all vertices you can reach from
   // v by traversing one edge.
   vector<char> neighbors(char v);
};

// constructor to initialize the matrix entries with -1 and vertex entries with false
graph::graph()
{
   // loop over the rows of matrix
   for(int i=0;i<26;i++)
   {
       vertex[i] = false; // set the vertices to false
       // loop over the columns of matrix
       for(int j=0;j<26;j++)
           matrix[i][j] = -1; // set the weight of each edge to -1 (initially no edge)
   }
}

// function to add a vertex to the graph
void graph:: addvertex(char v)
{
   int idx = (int)(v-'A'); // get the index of the letter relative to 'A'
   // check if it is valid upper case letter
   if(idx >= 0 && idx < 26)
       vertex[idx] = true; // if valid set the vertex entry to true
}

// function to add an edge from vertex to vertex with weight
void graph:: addedge(char from, char to, int weight)
{
   int fromIdx = (int)(from-'A'); // get the index of from vertex in the vertex array
   int toIdx = (int)(to-'A'); // get the index of to vertex in the vertex array

   // check both from and to vertex are valid uppercase letter and both vertex are added to the graph
   if(fromIdx >=0 && fromIdx < 26 && toIdx >=0 && toIdx < 26 && vertex[fromIdx] && vertex[toIdx])
   {
       matrix[fromIdx][toIdx] = weight; // if all valid then set the weight in matrix
   }
}

// function to return the weight from vertex from to vertex to
int graph::getweight(char from, char to)
{
   int fromIdx = (int)(from-'A'); // get the index of from vertex in the vertex array
   int toIdx = (int)(to-'A'); // get the index of to vertex in the vertex array

   // check both from and to vertex are valid uppercase letter and both vertex are added to the graph
   if(fromIdx >=0 && fromIdx < 26 && toIdx >=0 && toIdx < 26 && vertex[fromIdx] && vertex[toIdx])
   {
       return matrix[fromIdx][toIdx]; // return the weight from matrix
   }

   return -1; // no edge exists
}

// function to return the vertices of the graph
vector<char> graph::vertices()
{
   vector<char> letterVertices; // create a vector of vertices
   // loop over the vertex array
   for(int i=0;i<26;i++)
   {
       if(vertex[i]) // if vertex if added
           letterVertices.push_back((char)(i+'A')); // add the corresponding vertex to the vector
   }

   return letterVertices;
}

// function to return the vertices that are neighbors to vertex v i.e. all vertices you can reach from
// v by traversing one edge.
vector<char> graph:: neighbors(char v)
{
   vector<char> letterNeighbors;

   int idx = (int)(v-'A'); // get the index of v in the vertex array
   // check that vertex v is valid uppercase letter and v is added to the graph
   if(idx >= 0 && idx < 26 && vertex[idx])
   {
       // loop over the columns of matrix
       for(int i=0;i<26;i++)
       {
           // if edge from v exists to vertex at ith index
           if(matrix[idx][i] > -1)
               letterNeighbors.push_back((char)('A'+i)); // add the corresponding letter to the vector
       }
   }

   return letterNeighbors;
}
//end of graph.h


//main.cpp is a read only file

#include <iostream>
#include <vector>
#include <string>

#include "graph.h"

using namespace std;

void outputGraph(graph& g)
{
vector<char> vertices = g.vertices();

cout << "**Vertices: ";

for (char c : vertices)
{
cout << c << " ";
}

cout << endl;

cout << "**Edges: ";

for (char v : vertices)
{
vector<char> neighbors = g.neighbors(v);

for (char n : neighbors)
{
int weight = g.getweight(v, n);
cout << "(" << v << "," << n << "," << weight << ") ";
}
}

cout << endl;
}


int main()
{
graph g;
string input;

//
// Input vertices as single uppercase letters: A B C ...
//
cout << "Enter vertices as single letters, separated by spaces, end with #> ";
cin >> input;

while (input != "#")
{
char vertex = input[0];

g.addvertex(vertex);

cin >> input;
}

cout << endl;

//
// Now input edges:
//
string src, dest, weight;

cout << "Enter edge as LETTER LETTER WEIGHT, or #> ";
cin >> src;

while (src != "#")
{
cin >> dest;
cin >> weight;

//cout << src << ", " << dest << ", " << weight << endl;

g.addedge(src[0], dest[0], stoi(weight));

cout << "Enter edge as LETTER LETTER WEIGHT, or #> ";
cin >> src;
}

cout << endl;

//
// Now dump the graph to output stream:
//
outputGraph(g);

//
// done:
//
return 0;
}

//end of main.cpp

Output:

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
C++ #include<iostream> #include<string> #include<fstream> #include<cstdlib> using namespace std; const int ROWS = 8; //for rows in...
C++ #include<iostream> #include<string> #include<fstream> #include<cstdlib> using namespace std; const int ROWS = 8; //for rows in airplane const int COLS = 4; void menu(); //displays options void displaySeats(char[][COLS]); void reserveSeat(char [ROWS][COLS]); int main() { int number=0; //holder variable char seatChar[ROWS][COLS]; for (int i = 0; i < ROWS; i++) { for (int j = 0; j < COLS; j++) { seatChar[i][j] = '-'; } } int choice; //input from menu bool repeat = true; //needed for switch loop while (repeat...
# Problem Description Given a directed graph G = (V,E) with edge length l(e) > 0...
# Problem Description Given a directed graph G = (V,E) with edge length l(e) > 0 for any e in E, and a source vertex s. Use Dijkstra’s algorithm to calculate distance(s,v) for all of the vertices v in V. (You can implement your own priority queue or use the build-in function for C++/Python) # Input The graph has `n` vertices and `m` edges. There are m + 1 lines, the first line gives three numbers `n`,`m` and `s`(1 <=...
Please use this template. In this exercise you are to use a vector to store integers...
Please use this template. In this exercise you are to use a vector to store integers entered by the user. Once you have filled the vector, ask the user for a value to search for. If found, remove the value from the vector, keeping all other values in the same relative order, and then display the remaining values. #include <iostream> #include <vector> #include <climits> using namespace std; //Fills vector with user input until user enters 0 (does not include 0...
No matter what I do I cannot get this code to compile. I am using Visual...
No matter what I do I cannot get this code to compile. I am using Visual Studio 2015. Please help me because I must be doing something wrong. Here is the code just get it to compile please. Please provide a screenshot of the compiled code because I keep getting responses with just code and it still has errors when I copy it into VS 2015: #include <iostream> #include <conio.h> #include <stdio.h> #include <vector> using namespace std; class addressbook {...
Write a template-based class that implements a template-based implementation of Homework 3 that allows for any...
Write a template-based class that implements a template-based implementation of Homework 3 that allows for any type dynamic arrays (replace string by the template in all instances below). • The class should have: – A private member variable called dynamicArray that references a dynamic array of type string. – A private member variable called size that holds the number of entries in the array. – A default constructor that sets the dynamic array to NULL and sets size to 0....
This code it's not working, fix it for me please #include <iostream> using namespace std; class...
This code it's not working, fix it for me please #include <iostream> using namespace std; class People {    string name;    double height; public:    void setName(string name)    {        this->name = name;    }    void setHeight(double height)    {        this->height = height;    }    double getHeight() {        return height;    }    string getName()    {        return name;    } }; int main() {    const int size...
Programming Exercise 2: implement the member function moveToNth(...) that removes the item marked by the cursor...
Programming Exercise 2: implement the member function moveToNth(...) that removes the item marked by the cursor and inserts it as the nth element of the list; test your implementation by turning the flag LAB3_TEST2 from 0 to 1 in config.h; - Programming Exercise 3: implement the ListArray member function find(...) that searches for the element given as a parameter; the search starts at the cursor and stops when it finds the element or at the end of the list; the...
Write a program that prompts the user to input a string and outputs the string in...
Write a program that prompts the user to input a string and outputs the string in uppercase letters. (Use dynamic arrays to store the string.) my code below: /* Your code from Chapter 8, exercise 5 is below. Rewrite the following code to using dynamic arrays. */ #include <iostream> #include <cstring> #include <cctype> using namespace std; int main() { //char str[81]; //creating memory for str array of size 80 using dynamic memory allocation char *str = new char[80]; int len;...
c++ program can you please explain how it works and the process? Question: You will design...
c++ program can you please explain how it works and the process? Question: You will design a program in C++ that plays hangman using classes (polymorphism and inheritance).... Hangman Game CODE: #include <iostream> #include <cstdlib> #include<ctime> #include <string> using namespace std; int NUM_TRY=8; //A classic Hangman game has 8 tries. You can change if you want. int checkGuess (char, string, string&); //function to check the guessed letter void main_menu(); string message = "Play!"; //it will always display int main(int argc,...
a. Define the class bankAccount to store a bank customer’s account number and balance. Suppose that...
a. Define the class bankAccount to store a bank customer’s account number and balance. Suppose that account number is of type int, and balance is of type double. Your class should, at least, provide the following operations: set the account number, retrieve the account number, retrieve the balance, deposit and withdraw money, and print account information. Add appropriate constructors. b. Every bank offers a checking account. Derive the class checkingAccount from the class bankAccount (designed in part (a)). This class...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT