In: Computer Science
problem should be done in C++
read in the adjacency matrix for a graph (with 5
vertices) from a file, "adjacency.txt". An example file is
here: adjacency.txt
This example file contains the following
matrix:
1 2 4 1 0
2 0 1 1 3
4 1 2 1 0
1 1 1 0 1
0 3 0 1 3
Store the information in a 2D array.
to return the degree of a vertex in a generic graph.
For example, the following :
cout << "vertex 3's degree: " <<
vertexDegree(G,3) << endl;
cout << "vertex 4's degree: " <<
vertexDegree(G,4) << endl;
should output:
vertex 3's degree: 4
vertex 4's degree: 10
thanks!
Program Screen Shot:
Sample Output:
Program Code to Copy:
#include <iostream>
#include <fstream> // for file IO
#define ROWS 5
#define COLS 5
//
using namespace std;
//
// function to determine the degree by
// summing the elements in row number v-1
// where v is the vertex id
int vertexDegree(int M[ROWS][COLS],int v){
int sum = 0;
int i = v-1; // obtain index from vertex`
for(int j=0;j<COLS;j++){
sum = sum + M[i][j]; // cumulative sum
}
return sum; // the degree
}
//
//
int main(){
//
int v1,v2,v3,v4,v5; // vertices
int G[ROWS][COLS]; // 2D matrix
// file operations
string inFileName = "adjacency.txt";
ifstream inFile;
inFile.open(inFileName); // open file
// read file until eof, reading integers per row
int i=0;
while
(inFile>>v1>>v2>>v3>>v4>>v5){
G[i][0] = v1;
G[i][1] = v2;
G[i][2] = v3;
G[i][3] = v4;
G[i][4] = v5;
i++;
}
// close file
inFile.close();
// output invoking the vertexDegree function
cout << "vertex 3's degree: " << vertexDegree(G,3)
<< endl;
cout << "vertex 4's degree: " << vertexDegree(G,4)
<< endl;
//
return 0;
}
------------------------------------------------------------------------------
COMMENT DOWN FOR ANY QUERY RELATED TO THIS ANSWER,
IF YOU'RE SATISFIED, GIVE A THUMBS UP
~yc~