Hamiltonian Cycle with fork - c

hellow friends
i want to write Hamiltonian Cycle for 5 vertexes with fork. and i want to create a process for each vertex to check is it true vertex in (hamCycleUtil function )or no. so i write this code but it has false output.i cant solve the problem .pleas help.how can i write this code true ?i just want create 5 process to check the vertexes.
/*
* C Program to Find Hamiltonian Cycle
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include<sys/types.h>
#include<unistd.h>
#define V 5
void printSolution(int path[]);
/*
* check if the vertex v can be added at index 'pos' in the Hamiltonian Cycle
*/
bool isSafe(int v, bool graph[V][V], int path[], int pos)
{
if (graph [path[pos-1]][v] == 0)
return false;
for (int i = 0; i < pos; i++)
if (path[i] == v)
return false;
return true;
}
/* solve hamiltonian cycle problem */
bool hamCycleUtil(bool graph[V][V], int path[], int pos)
{
int pid;
int s=-1;//counter
if (pos == V)
{
if (graph[ path[pos-1] ][ path[0] ] == 1)
return true;
else
return false;
}
for (int v = 1; v < V; v++)
{
pid=fork();
s++;
if(s<V)// to control the number of fork
{
if(v==1)
{
pid=1;}
pid=fork();
s++;
if(pid < 0) {
printf("Error");
}
else if (pid == 0){
if (isSafe(v, graph, path, pos))
{
path[pos] = v;
if (hamCycleUtil (graph, path, pos+1) == true)
return true;
path[pos] = -1;
}
}
else {
if (isSafe(v, graph, path, pos))
{
path[pos] = v;
if (hamCycleUtil (graph, path, pos+1) == true)
return true;
path[pos] = -1;
}
}
}
}
return false;
}
/* solves the Hamiltonian Cycle problem using Backtracking.*/
bool hamCycle(bool graph[V][V])
{
int *path = malloc(V*sizeof(int));
for (int i = 0; i < V; i++)
path[i] = -1;
path[0] = 0;
if (hamCycleUtil(graph, path, 1) == false)
{
printf("\nSolution does not exist");
return false;
}
printSolution(path);
return true;
}
/* Main */
void printSolution(int path[])
{
printf("Solution Exists:");
printf(" Following is one Hamiltonian Cycle \n");
for (int i = 0; i < V; i++)
printf(" %d",path[i]);
printf(" %d",path[0]);
}
int main()
{
/* Let us create the following graph
(0)--(1)--(2)
| / \ |
| / \ |
| / \ |
(3)-------(4) */
bool graph1[V][V] = {{0, 1, 0, 1, 0},
{1, 0, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 1, 0, 0, 1},
{0, 1, 1, 1, 0},
};
{ hamCycle(graph1);
/* Let us create the following graph
(0)--(1)--(2)
| / \ |
| / \ |
| / \ |
(3) (4) */
bool graph2[V][V] = {{0, 1, 0, 1, 0},
{1, 0, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 1, 0, 0, 0},
{0, 1, 1, 0, 0},
};
hamCycle(graph2);
return 0;
}}

Related

Copy array's data with memmove function

I wrote my implementation of vector ( dynamicly growing array) for integer type. And I was faced with a problem when using memmove and memcpy functions for data reallocation goals. Memmmove and memcpy functions work as not expected. So i replaced it with for and now it works properly. But what is the why memove works this way ?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct vector {
int v_size;
int v_length;
int* v_data;
} vector;
typedef vector *vect;
vect
new_vector(int size) {
vect tmp = (vector*)malloc(sizeof(vector));
tmp->v_size = size;
tmp->v_length = 0;
tmp->v_data = (int*)malloc(sizeof(int) * size);
return tmp;
}
void
add_velem(vect tmp, int elem) {
if(tmp->v_length != tmp->v_size) {
tmp->v_data[tmp->v_length] = elem;
tmp->v_length += 1;
} else {
tmp->v_size = tmp->v_size * 2;
tmp->v_length += 1;
int *new_vector = (int*)malloc(sizeof(int) * tmp->v_size);
memmove(new_vector, tmp->v_data, tmp->v_length); // GOT INPUT LIKE THIS:
// 500, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
// ALOT OF ZERO
/*
for(int i = 0; i < tmp->v_length; i++) {
new_vector[i] = tmp->v_data[i];
}*/ // BUT GOT RIGHT INPUT WHEN USING FOR. WHAT IS THE REASON?
free(tmp->v_data);
tmp->v_data = new_vector;
tmp->v_data[tmp->v_length - 1] = elem;
}
return;
}
int
get_vlength(vect tmp) {
return tmp->v_length;
}
int
get_vsize(vect tmp) {
return tmp->v_size;
}
int
get_velem(vect tmp, int elem) {
if(tmp->v_data == NULL) {
fprintf(stderr, "Index out of range!\n");
}else if(elem >= tmp->v_length) {
fprintf(stderr, "Index is out of range!\n");
return -1;
}
return tmp->v_data[elem];
}
void
delete_vector(vect tmp) {
free(tmp->v_data);
tmp->v_data = NULL;
free(tmp);
tmp = NULL;
}
int
main(void) {
vect example = new_vector(10);
printf("lenth of vector is %d\n", get_vlength(example));
add_velem(example, 500);
printf("element %d is pushed into vector\n", 500);
printf("size of vector is %d and\nlength of vector is %d\n", get_vsize(example), get_vlength(example));
int velem = get_velem(example, 0);
printf("elem 0 of vector is %d\n", velem);
for(int i = 1; i < 30; i++) {
add_velem(example, i);
}
printf("length of vector is %d now\n", get_vlength(example));
for(int i = 0; i < get_vlength(example); i++) {
printf("%d, ", get_velem(example, i));
}
delete_vector(example);
return 0;
}

Adding two polynomials in C, Abort trap: 6

I am trying to add 2 polynomials using int arrays. For example,
co1[ ] = {5, 3, 2, 0, 0, 0, ...} & ex1[ ] = {6, 2, 1, 0, 0, 0, ...} represents the polynomial 5x^6 + 3x^2 + 2x. I tried doing this in different ways but I keep getting the message "Abort trap: 6" whenever I try to use this function. Any help would be appreciated. Thank you.
void add_polynom( int co1[ ], int ex1[ ], int co2[ ], int ex2[ ] )
{
int tmpC[ASIZE]; //ASIZE = 50
int tmpE[ASIZE];
int i, j, k, b, x = 0;
init_polynom(tmpC, tmpE); //sets all values within tmpC and tmpE to 0
for(i=0;i<ASIZE;i++)
{
for(j=0;j<ASIZE;j++)
{
if(ex1[i] > ex2[j])
{
tmpC[x] = co1[i];
tmpE[x] = ex1[i];
x++;
}
else if(ex1[i] == ex2[j])
{
if((ex1[i] == 0) && (ex2[j] == 0))
{
if(k == 0)
{
tmpC[x] = co1[i] + co2[j];
tmpE[x] = 0;
x++;
k = 1;
}
else
{
goto jump;
}
}
else
{
tmpC[x] = co1[i] + co2[j];
tmpE[x] = ex1[i];
x++;
}
}
else if(ex1[i] < ex2[j])
{
tmpC[x] = co2[j];
tmpE[x] = ex2[j];
x++;
}
}
}
jump:
for(b=0;b<ASIZE;b++)
{
co1[b] = tmpC[b];
ex1[b] = tmpE[b];
}
}
try to give k a value before entering the loop
In your inner loop you're incrementing x beyond ASIZE yet you use it to index into arrays you created with a length of ASIZE.

Wave Algorithm (Lee's Algorithm): incorrect final matrix

I'm writing a program calculating the shortest way from point A to point B.
I have a map (matrix) with values:
0 is block (wall, no way to pass);
1 is free way (you can pass);
2 is start point;
In the code below I declare 2 arrays: an array " map"and changed array "visited" while running program demonstrating visited points.
I check the cells in 4 directions (not diagonals) for 1 or 0. If it's 1 (possible to pass), I increase the counter for 1. For do not count the previous cell I'm trying to avoid it by the condition. I realized that in two one-dimensional arrays {1 0 -1 0} and { 0, 1, 0, -1 } to check neighbor points (what mean i check [i+1][j], [i-1][j], [i][j+1] and [i][j-1]).
As a result I wanna see "visited" matrix with a few lines which shows the way to reach to the point B (1, 2, 3, ... 15). I wanna find the way to map[7][7] point.
Right now the error here that I do count++ for the previous position. How to avoid that?
Thank you.
P.S. I wrote a few functions implementing a new array with 0 values, counting free to go cells and printing arrays.
main.c:
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#define WIDTH 8
#define HEIGHT 8
int mapZero(int map[WIDTH][HEIGHT]);
int mapPrint(int map[WIDTH][HEIGHT]);
int mapInit(int map[WIDTH][WIDTH]);
int findFreeToGoCells(int map[WIDTH][HEIGHT]);
int main(int argc, char * argv[])
{
bool stop;
unsigned int count;
unsigned int max;
int visited[WIDTH][HEIGHT];
int map[WIDTH][HEIGHT] =
{
{ 1, 1, 1, 1, 1, 0, 0, 1 },
{ 0, 1, 1, 1, 1, 1, 0, 1 },
{ 0, 0, 1, 0, 1, 1, 1, 0 },
{ 1, 0, 1, 1, 1, 0, 1, 1 },
{ 0, 0, 0, 1, 0, 0, 0, 1 },
{ 1, 0, 1, 1, 1, 0, 0, 1 },
{ 0, 0, 0, 0, 1, 0, 0, 1 },
{ 0, 1, 1, 1, 1, 1, 1, 1 },
};
mapZero(visited);
printf("Matrix of zeroed-visited cells:\n\n");
mapPrint(visited);
printf("Matrix of the map:\n\n");
mapPrint(map);
printf("Free to go cells: %d\n\n", findFreeToGoCells(map));
max = WIDTH * HEIGHT - 1;
visited[0][0] = map[0][0];
count = 0;
visited[0][0] = 0;
int di[4] = { 1, -1, 0, 0 };
int dj[4] = { 0, 0, 1, -1 };
//do
{
for (int i = 0; i < WIDTH; ++i)
{
for (int j = 0; j < HEIGHT; ++j)
{
if (visited[i][j] == count)
{
for (int k = 0; k < 4; ++k)
{
int i_check = i + di[k];
int j_check = j + dj[k];
if ((i_check >= 0 && i_check < WIDTH) && (j_check >= 0 && j_check < HEIGHT) && (map[i_check][j_check] != 0))
{
visited[i_check][j_check] = count + 1;
}
}
count++;
}
}
}
}// while (visited[7][7] == 0);
if (count > max + 99999)
printf("The way couldn't be found\n");
else
{
printf("Matrix of visited cells:\n\n");
mapPrint(visited);
printf("Free to go cells from [0][0] to [7][7]: %d\n", findFreeToGoCells(visited));
}
/*************************************************************************************/
/*************************************************************************************/
int len;
int x = 7;
int y = 7;
int x_path[WIDTH * HEIGHT];
int y_path[WIDTH * HEIGHT];
len = visited[7][7];
count = len;
while (count > 0)
{
x_path[count] = x;
y_path[count] = y;
count--;
for (int k = 0; k < 4; ++k)
{
int i_check = x + di[k];
int j_check = y + dj[k];
if ((i_check >= 0 && i_check < WIDTH) && (j_check >= 0 && j_check < HEIGHT) && (map[i_check][j_check] == count))
{
x = x + di[k];
y = y + dj[k];
break;
}
}
}
x_path[0] = 0;
y_path[0] = 0;
printf("\nThe shortest way consist of %d cells\nThere are %d the shortest way to reach th the final point\n\n", len, findFreeToGoCells(visited)-len);
system("pause");
return 0;
}
int mapZero(int map[WIDTH][HEIGHT])
{
for (int i = 0; i < WIDTH; ++i)
{
for (int j = 0; j < HEIGHT; ++j)
{
map[i][j] = 0;
}
}
return 0;
}
int mapPrint(int map[WIDTH][HEIGHT])
{
for (int i = 0; i < WIDTH; ++i)
{
for (int j = 0; j < HEIGHT; ++j)
{
printf("%2d ", map[i][j]);
}
printf("\n\n");
}
printf("\n");
return 0;
}
int findFreeToGoCells(int map[WIDTH][HEIGHT])
{
int count = 0;
for (int i = 0; i < WIDTH; ++i)
{
for (int j = 0; j < HEIGHT; ++j)
{
if (map[i][j] != 0) count++;
}
}
return count;
}
Result:

Kruskal Algorithm (set division)

I have a problem to understand Kruskal Algorithm. Here is the code
#include <stdio.h>
#define MAX_VERTICLES 100
#define INF 1000
int parent[MAX_VERTICLES];
int num[MAX_VERTICLES];
void setInit(int n) {
int i;
for (i = 0; i < n; i++) {
parent[i] = -1;
num[i] = 1;
}
}
int setFind(int vertex) {
int p, s, i = -1;
for (i = vertex;(p = parent[i]) >= 0; i = p)
;
s = i;
for (i = vertex;(p = parent[i]) >= 0; i=p)
parent[i]=s;
return s;
}
void setUnion(int s1, int s2) {
if (num[s1] < num[s2]) {
parent[s1]=s2;
num[s2]+=num[s1];
}
else {
parent[s2] = s1;
num[s1] += num[s2];
}
}
typedef struct {
int key;
int u;
int v;
}element;
#define MAX_ELEMENT 100
typedef struct {
element heap[MAX_ELEMENT];
int heap_size;
}HeapType;
void init(HeapType *h) {
h->heap_size = 0;
}
void printHeap(HeapType *h) {
int i;
int level = 1;
printf("\n==========");
for (i = 1; i <= h->heap_size;i++) {
if (i = level) {
printf("\n");
level *= 2;
}
printf("\t%d", h->heap[i].key);
}
printf("\n==========");
}
void insertMinHeap(HeapType *h, element item) {
int i;
i = ++(h->heap_size);
while ((i != 1) && (item.key < h->heap[i / 2].key)){
h->heap[i] = h->heap[i / 2];
i /= 2;
}
h->heap[i] = item;
}
element deleteMinHeap(HeapType *h) {
int parent, child;
element item, temp;
item = h->heap[1];
temp = h->heap[(h->heap_size)--];
parent = 1;
child = 2;
while (child <= h->heap_size) {
if ((child < h->heap_size) && (h->heap[child].key > h->heap[child + 1].key))
child++;
if (temp.key <= h->heap[child].key) break;
h->heap[parent] = h->heap[child];
parent = child;
child *=2;
}
h->heap[parent] = temp;
return item;
}
void insertHeapEdge(HeapType *h, int u, int v, int weight) {
element e;
e.u = u;
e.v = v;
e.key = weight;
insertMinHeap(h, e);
}
void insertAllEdges(HeapType *h){
insertHeapEdge(h, 0, 1, 13);
insertHeapEdge(h, 1, 2, 36);
insertHeapEdge(h, 2, 3, 12);
insertHeapEdge(h, 2, 4, 28);
insertHeapEdge(h, 3, 5, 32);
insertHeapEdge(h, 4, 5, 14);
insertHeapEdge(h, 0, 5, 19);
insertHeapEdge(h, 0, 6, 23);
insertHeapEdge(h, 1, 6, 15);
insertHeapEdge(h, 5, 6, 20);
}
void kruskal(int n) {
int edge_accepted = 0;
HeapType h;
int uset, vset;
element e;
init(&h);
insertAllEdges(&h);
setInit(n);
while (edge_accepted<(n-1)){
e = deleteMinHeap(&h);
uset = setFind(e.u);
vset = setFind(e.v);
if (uset != vset) {
printf("(%d,%d) %d \n", e.u, e.v, e.key);
edge_accepted++;
setUnion(uset, vset);
}7
}
}
void main(){
kruskal(7);
getchar();
}
I cannot understand how setFind and setUnion functions work.(the other things are fine)
Somebody can explain the algorithms explicitly, please?
The algorithm by Kruskal (which aims at the generation of a minimum spanning tree) needs subroutines for finding the connected component for a given vertex and the possibility to merge connected components.
Apparently, parent[i] stores one single vertex which can be followed until no parent is possible; the node which is reached this way is the root of the connected component - this node can be found via setFind; num[i] represents the number of children defined by this relation. Thus, the connected components are represented implicity.
The function setUnion aims at merging the smaller connected component into the larger one by attaching the root of one connected component to the other component and updating the number of children.

Dynamic List <malloc.h> free triggered a breakpoint - C Programming

Could someone help me with this one. I'm making BFS algorithm in C programming language, with help of dynamic lists.
This is my code.
// ConsoleApplication3.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <malloc.h>
#define n 6
typedef struct field
{
int x;
int y;
int dist;
struct field *next;
}Field;
// Get row and column number of 4 neighbours
int rows[] = { -1, 0, 0, 1 };
int cols[] = { 0, -1, 1, 0 };
Field *addToEnd(Field *lst, Field field)
{
Field *newField = (Field*)malloc(sizeof Field);
newField = &field;
newField->next = NULL;
if (!lst)
return newField;
else
{
Field *current;
for (current = lst; current->next; current = current->next);
current->next = newField;
return lst;
}
}
// Check if field is/isn't out of range
bool isValid(int row, int col)
{
return (row >= 0) && (row < n) && (col >= 0) && (col < n);
}
int BFS(int mat[][n], Field source, Field destination)
{
bool visited[n][n];
memset(visited, false, sizeof visited);
// Mark the source field as visited
visited[source.x][source.y] = true;
// Create dynamic list
Field *lst = NULL;
source.dist = 0;
// Adding the source field to the list
lst = addToEnd(lst, source);
while (lst)
{
// Getting first element in the list
Field current = *lst;
// If destination is reached then end function
if (current.x == destination.x && current.y == destination.y)
return current.dist;
// Delete first element of the list
Field *toDelete;
toDelete = lst;
lst = lst->next;
free(toDelete);
for (int i = 0; i < 4; i++)
{
int row = current.x + rows[i];
int col = current.y + cols[i];
// If adjacent field is valid, has path and isn't visited add it to the list
if (isValid(row, col) && mat[row][col] == 0 && !visited[row][col])
{
visited[row][col] = true;
Field adjField = { row, col, current.dist + 1 };
lst = addToEnd(lst, adjField);
}
}
}
// Return -1 if destination can't be reached
return -1;
}
int main()
{
int mat[n][n] =
{
{ 0, 0, 0, 0, 0, 0 },
{ 0, 1, 1, 1, 1, 0 },
{ 0, 1, 0, 0, 0, 0 },
{ 0, 0, 0, 1, 1, 0 },
{ 0, 1, 0, 0, 0, 0 },
{ 0, 0, 0, 1, 1, 0 }
};
Field start = { 1, 0 }, end = { 5, 5 };
int number = BFS(mat, start, end);
if (number != -1)
printf("%d\n", number);
else
printf("Destination can't be reached\n");
return 0;
}
Everything except part of code which need to delete first element of list is working. The problem is with free function.
https://i.stack.imgur.com/QpK1j.png
https://i.stack.imgur.com/HXp8d.png
Does anyone have an idea what could be possible wrong with this and how can I fix it?

Resources