I'm trying to detect and print a cycle in an undirected path, starting from a given vertex. So far, the path is recorded in a vector. The code seems to work, but there's one more vertex reported than it should be.
For the given example, one expected path would be: -1,6,0,5,3 which also put out: -1,6,0,5,3,2 but there's one more vertex than expected.
Maybe somebody has an idea how this can be fixed.
Thanks in advance!
#include <vector>
#include <iostream>
class Vertex
{
public:
Vertex() {};
Vertex(int x, int y, bool visited) : _x(x), _y(y){}
int _x;
int _y;
};
class Edge
{
public:
Edge(Vertex* from, Vertex* to): _from(from), _to(to){}
Vertex* _from;
Vertex* _to;
};
class MyGraph
{
public:
void addVertex(int x, int y, bool visited);
void addEdge(Vertex* vp1, Vertex* vp2);
bool dfs(int v, int p);
std::vector<std::vector<int>> g;
bool* visited;
std::vector<Edge> edges;
std::vector<Vertex> vertices;
std::vector<int>path;
};
void MyGraph::addVertex(int x, int y, bool visited)
{
Vertex v = Vertex(x, y, visited);
this->vertices.push_back(v);
}
void MyGraph::addEdge(Vertex* vp1, Vertex* vp2)
{
Edge e = Edge(vp1, vp2);
this->edges.push_back(e);
}
bool MyGraph::dfs(int v, int p)
{
visited[v] = true;
this->path.push_back(p);
for (int i = 0; i < (int)g[v].size(); i++)
{
if (!visited[g[v][i]])
{
dfs(g[v][i], v);
return true;
}
if (g[v][i] != p)
{
return true;
}
}
this->path.pop_back();
return false;
}
int main(int argc, char** argv)
{
MyGraph mg;
mg.addVertex(3, 0, false);
mg.addVertex(0, 1, false);
mg.addVertex(2, 1, false);
mg.addVertex(0, 2, false);
mg.addVertex(1, 2, false);
mg.addVertex(3, 2, false);
mg.addVertex(0, 0, false);
mg.g.resize(mg.vertices.size());
mg.g[0].push_back(5);
mg.g[0].push_back(6);
mg.g[1].push_back(2);
mg.g[1].push_back(3);
mg.g[1].push_back(6);
mg.g[2].push_back(1);
mg.g[3].push_back(2);
mg.g[3].push_back(4);
mg.g[3].push_back(5);
mg.g[3].push_back(6);
mg.g[4].push_back(3);
mg.g[4].push_back(5);
mg.g[5].push_back(0);
mg.g[5].push_back(3);
mg.g[5].push_back(4);
mg.g[6].push_back(0);
mg.g[6].push_back(1);
mg.g[6].push_back(3);
// expected path: 6,0,5,3
mg.visited = new bool[mg.vertices.size()]{false};
std::vector<int> pppath;
std::cout << mg.dfs(6, -1) << std::endl;
for (auto n : mg.path)
{
std::cout << n << ",";
}
return 0;
}
Thanks for your input. The problem has been solved. The push_back has to happen a line later in the for loop. Nonetheless, the code has the problem that the adjacency list has to be created on a certain order to avoid jumping back directly to the starting point.
Related
So I've been trying to implement Kruskal's algorithm, first I want to make clear the question is not related to the implementation of the algorithm. I've created one graph.hpp file, one kruskalsAlgo.hpp and main.cpp as follows respectively:
#pragma once
struct Edge
{
int source;
int destination;
int weight;
};
struct Graph
{
int V;
int E;
Edge* edge;
};
Graph* create_graph(int V, int E)
{
Graph* graph = new Graph;
graph -> V = V;
graph -> E = E;
graph -> edge = new Edge[E];
return graph;
}
#include <stdlib.h>
#include <tuple>
#include "../Graph/Graph.hpp"
class Kruskals_Algo
{
private:
struct subset
{
int parent;
int rank;
};
void make_set(subset*, int);
int find_set(subset*, int);
void _union(subset*, int, int);
public:
Edge* kruskal(Graph*);
void print_kruskals_MST(Edge*, int);
};
void Kruskals_Algo::make_set(subset* subsets, int V)
{
subsets[V].parent = V;
subsets[V].rank = 0;
}
int Kruskals_Algo::find_set(subset* subsets, int V)
{
if(subsets[V].parent != V)
subsets[V].parent = find_set(subsets, subsets[V].parent);
return subsets[V].parent;
}
void Kruskals_Algo::_union(subset* subsets, int x, int y)
{
int xroot = find_set(subsets, x);
int yroot = find_set(subsets, y);
if(subsets[xroot].rank < subsets[yroot].rank)
subsets[xroot].parent = yroot;
else if(subsets[xroot].rank > subsets[yroot].rank)
subsets[yroot].parent = xroot;
else
{
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
}
}
inline int myComp(const void* a, const void* b)
{
Edge* a1 = (Edge*)a;
Edge* b1 = (Edge*)b;
return a1 -> weight > b1 -> weight;
}
Edge* Kruskals_Algo::kruskal(Graph* graph)
{
int V = graph -> V;
Edge result[V];
Edge* result_ptr = result;
int e = 0;
int i = 0;
qsort(graph -> edge, graph -> E, sizeof(graph -> edge[0]), myComp);
subset* subsets = new subset[(V * sizeof(subset))];
for (int v = 0; v < V; ++v)
make_set(subsets, v);
while(e < V - 1 && i < graph -> E)
{
Edge next_edge = graph -> edge[i++];
int x = find_set(subsets, next_edge.source);
int y = find_set(subsets, next_edge.destination);
if (x != y)
{
result[e++] = next_edge;
_union(subsets, x, y);
}
}
//return std::make_tuple(res, e);
return result_ptr;
}
void Kruskals_Algo::print_kruskals_MST(Edge* r, int e)
{
int minimumCost = 0;
for(int i=0; i<e; ++i)
{
std::cout << r[i].source << " -- "
<< r[i].destination << " == "
<< r[i].weight << std::endl;
minimumCost = minimumCost + r[i].weight;
}
std::cout << "Minimum Cost Spanning Tree: " << minimumCost << std::endl;
}
#include <iostream>
#include "Graph/Graph.hpp"
#include "Kruskals_Algo/kruskalsAlgo.hpp"
//#include "Prims_Algo/primsAlgo.hpp"
using namespace std;
class GreedyAlgos
{
public:
void kruskals_mst();
//void prims_mst();
};
void GreedyAlgos::kruskals_mst()
{
Kruskals_Algo kr;
int V;
int E;
int source, destination, weight;
cout << "\nEnter the number of vertices: ";
cin >> V;
cout << "\nEnter the number of edges: ";
cin >> E;
Edge* res;
Graph* graph = create_graph(V, E);
for(int i=0; i<E; i++)
{
cout << "\nEnter source, destinstion and weight: ";
cin >> source >> destination >> weight;
graph -> edge[i].source = source;
graph -> edge[i].destination = destination;
graph -> edge[i].weight = weight;
}
//std::tie(result, E) = kr.kruskal(graph);
res = kr.kruskal(graph);
kr.print_kruskals_MST(res, E);
}
int main()
{
int choice;
GreedyAlgos greedy;
greedy.kruskals_mst();
return 0;
}
So my question here is when I debug the program the values in Edge result[V], which is a structure array, are calculated correctly, at position [0] [1] [2] as in the following picture:
but when the function print_kruskals_MST(res, E) is called from the main the values printed are different:
Is there any pointer thing that I'm doing wrong?
Thanks in advance!
P.S. Ignore the comments!
This answer might not answer your question directly but it should shed some light on the problem.
First of all, yes you have a lot of pointer problems...
Secondly, pair ANY use of the new operator with the delete operator. As it stands, you have a bunch of memory leaks.
Also, why create_graph? Create a constructor for Graph instead (and a destructor since the class has an Edge* edge it needs to take care of).
struct Graph
{
int V;
int E;
Edge* edge;
// constructor
Graph(int V, int E)
{
this->V = V;
this->E = E;
this->edge = new Edge[E];
}
// destructor
~Graph()
{
// nullify the member variable before deleting its memory is just a safety measure pertaining to multithreading.
Edge* _edge = this->edge;
this->edge = nullptr;
delete _edge;
}
};
Then change Graph* graph = create_graph(V, E); into Graph* graph = new Graph(V, E); and do delete graph when you're done using it.
Make sure you remove all memory leaks and we can go on to discussing referencing the correct data (f.ex. by me changing my answer).
using namespace std;
bool *marked;
//graph API
class Digraph
{
int v;
vector<int>* adj;
int e;
public:
Digraph(int V)
{
e=0;
v=V;
adj=new vector<int>[v];
}
void addEdge(int v,int w)
{
adj[v].push_back(w);
e++;
}
int V()
{
return v;
}
vector<int> adjacent(int i)
{
return adj[i];
}
};
//API ends
//this is the problem
void dfs(Digraph g,int s)
{
marked[s]=true;
for(int w:g.adjacent(s))
{
if(!marked[w])
dfs(g,w);
}
}
The Dfs here would run perfectly when traversing nodes but when returning it would stop at one node before the last and my program halts.I compiled it on codeblocks ide.
For ex
consider a graph going 1->2->3->4->0->1
when traversing its fine but when returning will stop at vertex 3
Actually i was implementing Cycles in a graph and topological sorts too. but none of them worked, and i have no idea why.
My code gives me free(): invalid pointer error (I don't call free, so my understanding is that it has something to do with how vectors operate internally). I am beginner to C++, so though I checked other answers to similar questions, I fail to see what exactly causes the issue.
I have a grid graph (i.e. vertex is connected with its 4-neighbors). Some vertices hold a special value, which is written done in a file in a form:
row columns value
The code:
graph::graph(const char *file_name) {
ifstream infile(file_name);
istringstream iss;
int R = 2; // number of rows
int C = 4; // number of columns
for (int i=0; i<R*C; i++) add_vertex(i+1);
adj = new std::vector<edge*>[R*C]; // adjacency list
// add all edges to the grid
for (int r=0; r<R; r++) {
for (int c=0; c<C; c++) {
if (c!=C-1) add_edge(vertices[r*C+c], vertices[r*C+(c+1)]);
if (r!=R-1) add_edge(vertices[r*C+c], vertices[(r+1)*C+c]);
}
}
int P = 2; // number of vertices holding a special value
for (int i=0; i<P; i++) {
getline(infile, line);
iss.str(line);
iss >> r >> c >> p;
vertices[r*C+c]->set_value(p);
p_vertices.push_back(vertices[r*C+c]);
iss.clear();
}
void graph::add_vertex(int v) {
auto *vert = new vertex(v);
vertices.push_back(vert);
}
void graph::add_edge(vertex *v, vertex *u) {
edge e = std::make_tuple(v, u, 1);
adj[v->get_id()].push_back(&e);
adj[u->get_id()].push_back(&e);
}
Header:
#include "vertex.h"
typedef std::tuple<vertex*, vertex*, int> edge;
class graph {
private:
std::vector<vertex*> vertices; // all vertices
std::vector<vertex*> p_vertices; // vertices with a special value
std::vector<edge*> *adj; // adjacency list
public:
explicit graph(const char *file_name);
void add_vertex(int v);
void add_edge(vertex *v, vertex *u);
};
Header for a vertex:
#include <string>
#include <vector>
class vertex {
private:
int id;
int val;
public:
explicit vertex(int id) {
this->id = id;
this->val = 0;
};
int get_id() { return id; };
void set_value(int p) { val = p; };
};
Example input:
0 0 1
1 2 3
The error disappears if I comment out this line:
p_vertices.push_back(vertices[r*C+c]);
And remains even if I try to change p_vertices to std::vector<int> instead of std::vector<vertex*> (and use p_vertices.push_back(r*C+c)).
Thanks for any hints on how to fix the error.
I was learning the dijkstra's algorithm and then in that there was the concept of priority queue with min_heap implementation where my priority_queue <Node,vector<Node>,comp> min_heap and the comp is a comparison struct;
struct Edge{
int src;
int dest;
int weight;
};
struct Node{
int vertex;
int weight;
};
class Graph{
public:
vector<vector<Edge>> adjList;
Graph(vector<Edge> &edges,int N){
adjList.resize(N);
for(auto &edge:edges){
adjList[edge.src].push_back(edge);
}
}
};
struct comp{
bool operator()(const Node &lhs,const Node &rhs) const{
return lhs.weight>rhs.weight;
}
};
void dij(Graph g,int source,int N){
priority_queue<Node,vector<Node>,comp> min_heap;
min_heap.push({source,0});
vector<int> dist(N,INT_MAX);
dist[source] = 0;
vector<bool> done(N,false);
done[0] = true;
while(!min_heap.empty()){
Node node = min_heap.top();
min_heap.pop();
int u = node.vertex;
for(auto i:g.adjList[u]){
int v = i.dest;
int weight = i.weight;
if(!done[u] && dist[u]+weight<dist[v]){
dist[v] = dist[u] + weight;
min_heap.push({v,dist[v]});
}
}
done[u] = true;
}
cout<<"The path from vertex "<<source<<" to "<<N<<" is "<<dist[N];
}
The code works fine and prints the minimum cost but I am not understanding the struct comp(); and how this works.
I am trying to solve a problem dealing with 2d vectors array.FunClass gets two parameters, number of sets and the lines per set.
The problem is whenever update_mytable function is being called a segmentation fault error pops up.During a quick search on stackoverflow I read that in most cases the issue for the seg-fault is because we are trying to access to a non-existed vector.But I don't think what I have the same issue here.
using std::vector;
typedef vector<mytable_entry>::iterator mytable_iter;
struct mytable_entry
{
int x_entry;
int y_entry;
};
mytable_entry new_mytable_entry(int new_ip, int new_target) {
mytable_entry new_entry;
new_entry.ip_entry = new_ip;
new_entry.target_entry = new_target;
return new_entry;
}
class FunClass : public BaseClass
{
public:
FunClass(unsigned mytable_sets, unsigned mytable_lines_per_set)
: table_sets(mytable_sets), table_assoc(mytable_lines_per_set)
{
mytable_table = vector< vector<mytable_entry> > (table_sets,vector< mytable_entry> (table_assoc));
}
~FunClass() {
/* Vectors will be decontructed automatially out of scope */
}
virtual bool predict(int x, int y) {
/* If mytable_entry exist return true, else false */
unsigned mytable_set_index = x % table_sets;
if (find_mytable_entry(mytable_table[mytable_set_index])) {
return true;
} else {
return false;
}
}
virtual void update(bool val1, bool val2, int x, int y) {
unsigned mytable_set_index = x % table_sets;
if (val1 == val2){
update_mytable_table(mytable_table[mytable_set_index],ip,target_entry,table_assoc);
}
void update_mytable(vector<mytable_entry> & mytable_set, int x, int y,unsigned table_assoc){
mytable_entry new_entry = new_mytable_entry(ip,target);
mytable_set.push_back(new_entry);
if (mytable_set.size() > table_assoc){
mytable_set.erase(mytable_set.begin());
}
}
bool find_mytable_entry(vector<mytable_entry> & mytable_set, int x) {
mytable_iter iter;
for (iter = mytable_set.begin(); iter != mytable_set.end(); iter++){
if ((*iter).ip_entry == ip) {
mytable_entry tmp_mytable_entry = (*iter);
mytable_set.erase(iter);
mytable_set.push_back(tmp_mytable_entry);
return true;
}
}
return false;
}
private:
vector< vector<mytable_entry> > mytable_table;
unsigned table_sets, table_assoc;
};
If I remove the mytable_set.push_back(new_entry); from update_mytable everything goes fine then.