I tried to run the bwlow code, but I am getting an error
'this' cannot be used in a constant expression
I need to implement a function that received intervals graph with coloring and also calculate the edges and max\minimum degree, but when I try to run the program I have a problem with this->V
. I need help, how can I fix this? I tried with vector
but was unsuccessful.
the error appear here
int result[V];
i tried to change to vector but i getting this error
#include <iostream>
#include <list>
using namespace std;
// A class that represents an undirected graph
class Graph {
int V; // No. of vertices
int** adj; // 2D adjacency matrix
public:
// Constructor and destructor
Graph(int V);
// ~Graph() { delete [] adj; }
void addEdge(int v, int w); // function to add an edge to graph
void greedyColoring(); // Prints greedy coloring of the vertices
};
Graph::Graph(int V)
{
this->V = V;
adj = new int*[V];
for (int i = 0; i < V; i++) {
adj[i] = new int[V];
}
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
adj[i][j] = 0;
}
}
}
void Graph::addEdge(int v, int w)
{
adj[v][w] = 1;
adj[w][v] = 1; //undirected graph
|
}
// Assigns colors (starting from 0) to all vertices and prints
// the assignment of colors
void Graph::greedyColoring()
{
int result[V];
// Assign the first color to first vertex
result[0] = 0;
// Initialize remaining V-1 vertices as unassigned
for (int u = 1; u < V; u++)
result[u] = -1; // no color is assigned to u
// A temporary array to store the available colors. True
// value of available[cr] would mean that the color cr is
// available to assign
bool available[V];
for (int cr = 0; cr < V; cr++)
available[cr] = true;
// Assign colors to remaining V-1 vertices
for (int u = 1; u < V; u++) {
// Process all adjacent vertices and flag their colors
// as unavailable
for (int i = 0; i < V; i++) {
if (adj[u][i]) {
if (result[i] != -1) {
available[result[i]] = false;
}
}
}
// Find the first available color
int cr;
for (cr = 0; cr < V; cr++)
if (available[cr] == true)
break;
result[u] = cr; // Assign the found color
// Reset the values back to true for the next iteration
for (int cr = 0; cr < V; cr++)
available[cr] = true;
}
// print the result
for (int u = 0; u < V; u++)
cout << "Vertex " << u << " ---> Color "
<< result[u] << endl;
}
// Driver program to test above function
int main()
{
Graph g1(5);
g1.addEdge(0, 1);
g1.addEdge(0, 2);
g1.addEdge(1, 2);
g1.addEdge(1, 3);
g1.addEdge(2, 3);
g1.addEdge(3, 4);
cout << "Coloring of graph 1 \n";
g1.greedyColoring();
}