Finding one Hamiltonian cycle in graph error - c

I have a program in C which reads definition of graph from file, search for Hamiltonian cycle (only one) and prints it on screen if found. Problem is that program is crashing when I'm trying to find cycle in graphs with 30 and more vertices (for 30 vertices it sometimes shows cycle end get crashed (with different saturations), for more get crashed instantly). When I try to debug it stops at free() function and shows SIGTRAP signal. What can I do to fix that? Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
typedef struct Lista
{
struct Lista * next;
int v;
} Lista;
Lista * stos;
bool *visited;
int wierzcholki, krawedzie;
int *S;
int sptr;
Lista **graf;
bool czyZnaleziono = false;
int DFSHamilton(int v)
{
if (!czyZnaleziono)
{
int i;
bool test;
Lista *p;
S[sptr++] = v;
if(sptr < wierzcholki)
{
visited[v] = true;
for(p = graf[v]; p; p = p->next)
if(!visited[p->v]) DFSHamilton(p->v);
visited[v] = false;
}
else
{
test = false;
for(p = graf[v]; p; p = p->next)
if(!(p->v))
{
test = true;
break;
}
if(test)
{
printf("Hamiltonian Cycle : ");
for(i = 0; i < sptr; i++)
{
printf("%d ",S[i]);
}
printf("0\n");
czyZnaleziono = true;
}
}
sptr--;
}
}
int main()
{
FILE *plik;
Lista *p, *r;
plik = fopen("rzeczy40-95.txt", "r");
double start, stop, czas;
int i, j, w1, w2;
sptr = 0;
visited = malloc(krawedzie*sizeof(bool));
if (plik == NULL)
{
printf("Nie mozna odnalezc pliku");
return 0;
}
else
{
fscanf(plik, "%d %d", &wierzcholki, &krawedzie);
S = malloc(wierzcholki*sizeof(int));
graf = malloc(wierzcholki*sizeof(Lista));
for(i=0; i<wierzcholki; i++)
{
graf[i] = NULL;
visited[i] = false;
}
for(j=0; j<krawedzie; j++)
{
fscanf(plik,"%d %d", &w1, &w2);
p = malloc(sizeof(Lista));
r = malloc(sizeof(Lista));
p->v = w2;
p->next = graf[w1];
graf[w1] = p;
r->v = w1;
r->next = graf[w2];
graf[w2] = r;
}
fclose(plik);
DFSHamilton(0);
free(visited);
free(S);
for (i = 0; i < wierzcholki; i++)
{
free(graf[i]);
}
free(graf);
return 0;
}
}

Related

VS17 not initializing pointer

My problem is that this code is not working in VS 2017 while in CLion it works.
VS says:
Severity Code Description Project File Line Suppression State
Error (active) E0144
a value of type void * cannot be used to initialize an entity of type queue_t*
therefor the program is not allocating the memory.
Further every pointer like the example above is not working.
Does somebody here know why that is the case, why VS thinks that this would be a void?
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
struct packet_t {
double d;
int i;
long l;
char *p;
struct queue_t *queue;
};
struct queue_t {
char *name;
int size;
int entries;
double time;
struct packet_t **packets;
int read;
int write;
long lost;
long total;
};
int decision = -1;
int isRunning = 1;
void logError(char message[]) {
printf("ERROR: %s", message);
}
struct queue_t *queue_create(char *name, int size) {
struct queue_t *q = malloc(sizeof(struct queue_t));
if (!q) {
logError("could not allocate memory!\n");
return 0;
}
else {
q->name = name;
q->size = size;
q->entries = 0;
q->read = 0;
q->write = 0;
q->total = 0;
q->lost = 0;
q->packets = malloc(size * sizeof(struct packet_t *));
if (!q->packets) {
logError("could not allocate memory!\n");
free(q);
return 0;
}
struct packet_t **current;
for (int i = 0; i < size; i++) {
current = q->packets + i;
*current = NULL;
}
}
return q;
}
int packet_destroy(struct packet_t *packet) {
//TODO test if deleted ?
if (packet) {
free(packet);
return 1;
}
return 0;
}
long queue_store(struct queue_t *queue, struct packet_t *packet) {
if (queue->entries < queue->size) {
packet->queue = queue;
*(queue->packets + queue->write) = packet;
queue->write++;
if (queue->write == queue->size) {
queue->write = 0;
}
queue->total++;
queue->entries++;
return queue->total;
}
//cant save packet ->destroy
packet_destroy(packet);
queue->lost++;
return 0;
}
struct packet_t *queue_retrieve(struct queue_t *queue) {
if (queue->entries == 0) return NULL;
struct packet_t **current = queue->packets + queue->read;
struct packet_t *packet = *current;
*current = NULL;
if (packet->queue) {
packet->queue = NULL;
}
queue->entries--;
queue->read++;
if (queue->read == queue->size) {
queue->read = 0;
}
return packet;
}
struct packet_t *packet_create(int i, double d, long l, char *p) {
struct packet_t *new = malloc(sizeof(struct packet_t));
if (new) {
new->i = i;
new->d = d;
new->l = l;
new->p = p;
}
else {
logError("failed to allocate memory");
}
return new;
}
int queue_destroy(struct queue_t *queue) {
if (!queue) {
logError("could not find queue!");
return 0;
}
struct packet_t *p;
for (int i = 0; i < queue->size; i++) {
p = *(queue->packets + i);
packet_destroy(p);
}
//TODO test if not needed as it's already free'd in packet_destroy
free(queue->packets);
free(queue);
return 0;
}
long test_queue(int val) {
int sum = 0, finalTime = 0;
clock_t startTime, finalTicks;
startTime = clock();
while (finalTime < val) {
struct queue_t *q = queue_create("test", 10);
queue_destroy(
sum++;
finalTicks = (clock() - startTime);
// printf("ticks: %d\n", finalTicks);
finalTime = (int)floor((finalTicks / (double)CLOCKS_PER_SEC));
// printf("time: %d\n", finalTime);
}
printf("Runtime: %d\n seconds", finalTime);
printf("Added and removed %d queues\n", sum);
}
long test_packets(int val) {
int finalTime = 0;
struct queue_t *q = queue_create("test", 10);
clock_t startTime, finalTicks;
startTime = clock();
while (finalTime < val) {
struct packet_t *t = packet_create(finalTime, finalTime + 1, finalTime + 2, NULL);
queue_store(q, t);
packet_destroy(queue_retrieve(q));
finalTicks = (clock() - startTime);
// printf("ticks: %d\n", finalTicks);
finalTime = (int)floor((finalTicks / (double)CLOCKS_PER_SEC));
// printf("time: %d\n", finalTime);
}
printf("Runtime: %d\n", finalTime);
printf("Successfully added %li entries\n", q->total);
printf("Failed to add %li entries\n", q->lost);
queue_destroy(q);
}
void resetDecision() {
decision = -1;
isRunning = 1;
}
void checkDecision() {
while (decision != 0 && decision != 1 && decision != 2) {
printf("Select option:\n (1) Run queue test \n (2) Run packet test \n(0) to cancel \n");
scanf("%d", &decision);
}
if (decision == 0) {
isRunning = 0;
}
else if (decision == 1) {
int val = 0;
while (val <= 0) {
printf("Enter the time to test");
scanf("%d", &val);
}
printf("Running test for %d seconds....\n", val);
test_queue(val);
}
else if (decision == 2) {
int val = 0;
while (val <= 0) {
printf("Enter the time to test");
scanf("%d", &val);
}
printf("Running test for %d seconds....\n", val);
test_packets(val);
}
if (decision != 0)
resetDecision();
}
int main() {
while (isRunning) {
checkDecision();
}
return 0;
}
You are compiling your program as a C++ program. In C++ there is no implicit conversion from the type void * to pointer of other object type.
So you need to write using explicit casting like
struct queue_t *q = ( struct queue_t * )malloc(sizeof(struct queue_t));
Or you should consider your program as indeed a C++ program and use the operator new instead of the C function malloc.

Linked List pointers prob

I do not know why this is not working.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// struct of list
typedef struct noeud
{
int adresse, taille, temp;
struct noeud* suivant;
} * liste;
int random(int a, int b)
{
return (a + (rand() % ((b + 1) + a)));
}
void initialisation(liste* LBO)
{
*LBO = NULL;
}
I think it's here the problem when I create q (q is created to point to the previous node).
void creation(liste* LBO)
{
liste q, prec = NULL;
int i = 0;
srand(time(NULL));
while (i < 3)
{
printf("%d", i);
q = malloc(sizeof(liste));
if (*LBO == NULL)
{
q->adresse = 0;
q->taille = random(5, 45);
q->temp = random(5, 15);
q->suivant = *LBO;
*LBO = q;
i++;
}
else
{
prec = *LBO;
q->taille = random(5, 45);
q->temp = random(5, 15);
q->adresse = prec->adresse + prec->taille;
q->suivant = *LBO;
*LBO = q;
i++;
}
}
}
void affichage(liste LBO)
{
printf("\nvoici ta liste \n ");
while (LBO != NULL)
{
printf("%d-->", LBO->taille);
LBO = LBO->suivant;
}
if (LBO == NULL)
printf("NULL");
}
int main()
{
// or here
printf("Hello world!\n");
liste LBO;
initialisation(&LBO);
creation(&LBO);
affichage(LBO);
return 0;
}
There are several issues:
Instead of calling
initialisation(&LBO);
which is not really wrong, just write:
LBO = NULL;
Then don't hide pointers with typedefs, it only adds confusion.
Instead of:
typedef struct noeud
{
int adresse, taille, temp;
struct noeud* suivant;
} *liste;
Write:
struct noeud
{
int adresse, taille, temp;
struct noeud* suivant;
};
and use struct noeud* instead of liste.
Now the real problem:
This is wrong. Here you allocate the size for a pointer, but you need to allocate the size for the whole structure:
q = malloc(sizeof(liste));
which is actually the same as:
q = malloc(sizeof(struct noeud*))
but you need:
q = malloc(sizeof(struct noeud))
You see now why hiding pointers with typedefs is a bad idea.
So here is the corrected version of your program (#includes ommitted for brevity):
struct noeud
{
int adresse, taille, temp;
struct noeud* suivant;
};
int random(int a, int b)
{
return (a + (rand() % ((b + 1) + a)));
}
void creation(struct noeud** LBO)
{
struct noeud* q, *prec = NULL;
int i = 0;
// srand(time(NULL)); <<<<< don't call srand here, call it once at the
// beginning of the program
while (i < 3)
{
printf("%d", i);
q = malloc(sizeof(struct noeud));
if (*LBO == NULL)
{
q->adresse = 0;
q->taille = random(5, 45);
q->temp = random(5, 15);
q->suivant = *LBO;
*LBO = q;
i++;
}
else
{
prec = *LBO;
q->taille = random(5, 45);
q->temp = random(5, 15);
q->adresse = prec->adresse + prec->taille;
q->suivant = *LBO;
*LBO = q;
i++;
}
}
}
void affichage(struct noeud* LBO)
{
printf("\nvoici ta struct noeud* \n ");
while (LBO != NULL)
{
printf("%d-->", LBO->taille);
LBO = LBO->suivant;
}
// if (LBO == NULL) <<<<<<<<<<< drop this, LBO is always NULL here
// but it doesn't hurt, it's just useless
printf("NULL");
}
int main()
{
srand(time(NULL)); // <<<<<<<<<<<<< call srand here
struct noeud* LBO;
LBO = NULL;
creation(&LBO);
affichage(LBO);
return 0;
}
There is still room for improvement, especially the creation function is somewhat awkward.
Also look at the comments with <<<<<<<<<<<, there are minor corrections

Using a DFS to compute distance from source node

I am trying to use a DFS algorithm to calculate the distance from a source node for each node. Currently it outputs a distance of 0 for the source vertex but 1 for all the other vertices, even though there should be a couple with a distance of 2. The printf in the DFS does print out the right order, with the source first then the vertices with distance 1 and then distance 2. So where in the algorithm would I need to put the distance increase.
void dfs(int vertex1) {
graph[vertex1-1].visited = 1;
printf("%d \n",vertex1);
struct edge *e;
e = graph[vertex1-1].edgePtr;
while (e) {
if (!(graph[e->vertexIndex - 1].visited)){
graph[e->vertexIndex - 1].distance++;
dfs(e->vertexIndex);
}
e = e->edgePtr;
}
}
I think I have figured out a way to make the DFS calculate the distance and it is correct except the last vertex found it says that the distance is 3 instead of 2.
5
(2,3)
(1,4)
(1,3)
(3,4)
(4,5)
#include <stdio.h>
#include <stdlib.h>
#include "../HW3/input_error.h"
#define VertexToSearch 1
typedef struct edge {
int vertexIndex;
struct edge *edgePtr;
} edge;
typedef struct vertex {
int vertexKey;
struct edge *edgePtr;
int visited;
int distance;
} vertex;
int vertexCount = 0;
struct vertex graph[];
void load_file(char*);
void insertEdge(int, int, struct vertex[]);
void InsertVertex(int, struct vertex[]);
void printGraph();
void dfs();
void print_distances();
enum error program_error;
int count;
int main(int argc, char** argv) {
load_file(argv[1]);
printGraph();
dfs(VertexToSearch);
print_distances();
return 0;
}
void load_file(char* filename) {
int vertex1;
int vertex2;
FILE* file = fopen(filename, "r");
if (file == NULL) {
printf("%s did not open\n", filename);
program_error = FILE_FAILED_TO_OPEN;
exit(program_error);
}
fscanf(file, "%d", &count);
graph[count];
for (int i = 0; i < count; i++) {
InsertVertex(i+1, graph);
}
for (int i = 0; i < count; i++) {
fscanf(file, "\n(%d,%d)", &vertex1, &vertex2);
insertEdge(vertex1, vertex2, graph);
}
fclose(file);
}
void InsertVertex(int vertexKey, struct vertex graph[]) {
graph[vertexCount].vertexKey = vertexKey;
graph[vertexCount].edgePtr = NULL;
graph[vertexCount].visited = 0;
graph[vertexCount].distance = 0;
vertexCount++;
}
void insertEdge(int vertex1, int vertex2, struct vertex graph[]) {
struct edge *e, *e1, *e2;
e = graph[vertex1 - 1].edgePtr;
while (e && e->edgePtr) {
e = e->edgePtr;
}
e1 = (struct edge *) malloc(sizeof (*e1));
e1->vertexIndex = vertex2;
e1->edgePtr = NULL;
if (e)
e->edgePtr = e1;
else
graph[vertex1 - 1].edgePtr = e1;
e = graph[vertex2 - 1].edgePtr;
while (e && e->edgePtr) {
e = e->edgePtr;
}
e2 = (struct edge *) malloc(sizeof (*e2));
e2->vertexIndex = vertex1;
e2->edgePtr = NULL;
if (e)
e->edgePtr = e2;
else
graph[vertex2 - 1].edgePtr = e2;
}
void printGraph() {
int i;
struct edge *e;
for (i = 0; i < vertexCount; i++) {
printf("%d(%d)", i+1, graph[i].vertexKey);
e = graph[i].edgePtr;
while (e) {
printf("->%d", e->vertexIndex);
e = e->edgePtr;
}
printf("\n");
}
}
void dfs(int vertex1) {
graph[vertex1 - 1].visited = 1;
printf("%d \n", vertex1);
struct edge *e;
e = graph[vertex1 - 1].edgePtr;
for (int i = 0; i < count; i++) {
if (graph[i].visited == 0 && e->vertexIndex != VertexToSearch) {
graph[i].distance++;
}
}
while (e) {
if (!(graph[e->vertexIndex - 1].visited)) {
dfs(e->vertexIndex);
}
e = e->edgePtr;
}
}
void print_distances(){
for(int i = 0;i < count; i++){
printf("%d %d\n", i+ 1,graph[i].distance);
}
}

Runtime Error 402 MASH uva

I just started doing uva problems. However in problem 402 no matter what I do the result of my submission is always runtime error. I cannot understand where is my problem or why is it resulting in errors. Can anyone help, please?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct nodo
{
int info;
struct nodo *sig;
};
struct nodo *p, *q, *nuevo;
void Insertar(int n)
{
int i; //Contador
struct nodo *nuevo;
for(i = 0; i < n; i++)
{
nuevo = (struct nodo*)malloc(sizeof(struct nodo));
nuevo->info = i+1;
if(!p)
p = nuevo;
else
q->sig=nuevo;
q = nuevo;
q->sig = 0;
}
}
void Borrar()
{
struct nodo *aux;
}
int main()
{
int m,s,cont=0,cartas[22],i,j,k;
while(scanf("%i %i",&m,&s)==2)
{
if(cont)
printf("\n");
cont++;
for(i = 0; i < 20; i++)
scanf("%i",&cartas[i]);
printf("Selection #%i\n",cont);
Insertar(m);
for(i = 0, s = m-s; i < 20 && s; i++)
{
j = cartas[i] - 2;
if(j == -1)
{
while(s)
{
nuevo=p->sig;
free(p);
p = nuevo;
s--;
}
}
else
{
nuevo = p;
while(nuevo->sig)
{
for(k = 0; k < j && nuevo->sig; nuevo = nuevo->sig, k++);
if(nuevo->sig)
{
q = nuevo->sig;
nuevo->sig = q->sig;
free(q);
nuevo = nuevo->sig;
s--;
if(!s)
break;
}
}
}
}
printf("%i",p->info);
nuevo = p->sig;
free(p);
while(nuevo)
{
printf(" %i",nuevo->info);
p = nuevo->sig;
free(nuevo);
nuevo = p;
}
printf("\n");
}
}

Unreachable Node in Dijkstra's Algorithm

So I'm having trouble with Dijkstra's algorithm (src to dest). I looked at other answers and could not find the solution to my problem. I have used an adjacency list, thus I have a list for vertices, and each vertex has it's own edge list. My problem arises when I have a node that is unreachable. Specifically, it never gets visited thus I'm stuck in my allNotComp while loop. Can anyone help me with a solution? Code is below.
#include <stdlib.h>
#include <stdio.h>
int INFINITY = 9999;
struct edge
{
int vertexIndex;
int vertexWeight;
struct edge *edgePtr;
} edge;
struct vertex
{
int vertexKey;
struct edge *edgePtr;
struct vertex *vertexPtr;
}vertex;
struct vertex *Start = NULL;
void insertEdge(int vertex, int vertex2, int vertexWeight);
void insertVertex(int vertexKey);
int allNotComp(int comp[], int size);
void printPath(int prev[], int src, int dest, int size);
void dijkstra(int src, int size, int dest);
int cost(int curr, int i);
int main(int argc, char * argv[]) {
int k = 1;
int numVertices = atoi(argv[2]);
char* source = argv[3];
char* destination = argv[4];
int src = atoi(argv[3]);
int dest = atoi(argv[4]);
Start = &vertex;
Start->vertexKey = 0;
Start->vertexPtr = NULL;
Start->edgePtr = NULL;
int m = 0;
int flag = 0;
int flag2 = 0;
for(m = 0; m < numVertices; m++){
if(src == m) {
flag = 1;
}
if(dest == m) {
flag2 = 1;
}
}
if(!(flag && flag2)) {
printf("%s ", "ERROR: Src and/or Dest not valid.\n");
exit(0);
}
while(k < numVertices) {
insertVertex(k);
k++;
}
FILE *f = fopen(argv[1], "r");
int numbers[numVertices][numVertices];
char ch;
int i = 0;
int j = 0;
for(m = 0; m < numVertices*numVertices; m++) {
fscanf(f, "%d", &(numbers[i][j]));
j=j+1;
if(j == numVertices) {
i=i+1;
j=0;
}
}
for(i=0;i<numVertices;i++) {
for(j=0;j<numVertices;j++) {
if(i == j && numbers[i][j] != 0) {
printf("%s", "ERROR: All diagonals must be zero.\n");
exit(0);
}
if(i != j) {
insertEdge(i, j, numbers[i][j]);
}
}
}
dijkstra(src, numVertices, dest);
}
void insertEdge(int vertex, int vertex2, int vertexWeight)
{
if(vertexWeight == -1) return;
struct vertex *traverse;
if(vertex == Start->vertexKey) {
traverse = Start;
}
else {
while(traverse->vertexKey != vertex) {
traverse = traverse->vertexPtr;
}
}
struct edge *e,*e1,*e2;
e=traverse->edgePtr;
while(e&& e->edgePtr)
{
e=e->edgePtr;
}
e1=(struct edge *)malloc(sizeof(*e1));
e1->vertexIndex=vertex2;
e1->vertexWeight = vertexWeight;
e1->edgePtr=NULL;
if(e)
e->edgePtr=e1;
else
traverse->edgePtr=e1;
}
void insertVertex(int vertexKey) {
struct vertex *v, *v1, *v2;
v = Start->vertexPtr;
while(v && v->vertexPtr) {
v=v->vertexPtr;
}
v1=(struct vertex *)malloc(sizeof(*v1));
v1->vertexKey = vertexKey;
v1->vertexPtr = NULL;
v1->edgePtr = NULL;
if(v) {
v->vertexPtr = v1;
}
else {
Start->vertexPtr = v1;
}
}
void dijkstra(int src, int size, int dest) {
int comp[size];
int dist[size];
int prev[size];
int i;
for(i = 0; i<size; i++) {
comp[i] = 0;
dist[i] = INFINITY;
prev[i] = -1;
}
comp[src] = 1;
dist[src] = 0;
prev[src] = src;
int curr = src;
int k;
int minDist;
int newDist;
while(allNotComp(comp, size)) {
minDist = INFINITY;
for(i = 0; i<size;i++) {
if(comp[i] == 0) {
newDist = dist[curr] + cost(curr, i);
if(newDist < dist[i]) {
dist[i] = newDist;
prev[i] = curr; }
if(dist[i] < minDist) {
minDist = dist[i];
k=i; }
}
}
curr = k;
comp[curr] = 1;
}
if(dist[dest] < INFINITY) {
printPath(prev, src, dest, size);
printf(":%d\n", dist[dest]);
} else {
printf("%s\n", "NO PATH EXISTS BETWEEN THE TWO VERTICES!");
}
}
int allNotComp(int comp[], int size) {
int i;
for(i = 0; i < size; i++) {
if(comp[i] == 0) {
return 1;
}
}
return 0;
}
int cost(int curr, int i) {
struct vertex *travel;
struct edge *traverse;
travel = Start;
while(travel->vertexPtr != NULL) {
if(travel->vertexKey != curr) {
travel = travel->vertexPtr;
}
else{
break;
}
}
traverse = travel->edgePtr;
while(traverse->edgePtr != NULL) {
if(traverse->vertexIndex != i) {
traverse = traverse->edgePtr;
}
else{
break;
}
}
if(traverse->vertexIndex != i) {
return INFINITY;
}
return traverse->vertexWeight;
}
void printPath(int prev[], int src, int dest, int size) {
if(src == dest) {
printf("%d", src);
}
else {
printPath(prev, src, prev[dest], size);
printf("-%d", dest);
}
}
Although an unreachable node never gets visited, this situation can be detected. If the dists of all unvisited nodes are INFINITY, this means all remaining nodes are unreachable, and you should end the loop.

Resources