Knights tour recursive - c

I'm trying to write knights tour recursive algorithm:
int mov[8][2] = {{2,1},{2,-1},{-2,1},{-2,-1},{1,2},{-1,2},{1,-2},{-1,-2}};
typedef struct element {
int x;
int y;
struct element *prev, *next;
} node;
//adding pool to list
void dEnd(node **root, int x,int y)
{
node *pos;
pos = *root;
while(pos->next!= NULL)
pos = pos->next;
pos->next = (node *)malloc(sizeof(node));
pos->next->x=x;
pos->next->y=y;
pos->next->prev=pos;
pos->next->next=NULL;
}
void uEnd(node **root,int x,int y)
{
node *pos;
pos = *root;
while(pos->x!= x && pos->y !=y)
{
pos = pos->next;
}
pos->prev->next=NULL;
free(pos);
}
void printAll(node **root)
{
node *pos = *root;
while(pos->next)
{
printf("%d %d\n", pos->x,pos->y);
pos = pos->next;
}
}
int contains(int x,int y)
{
return(((x >= 0 ) && (x <= 7)) && ((y >= 0) && (y <= 7)));
}
//find move
int searchForMove(int x, int y, int **tab, node **list, int *number)
{
int i ;
for(i = 0; i < 8; i++)
{
int nx, ny;
nx = x + mov[i][0];
ny = y + mov[i][1];
if(contains(nx, ny) && !tab[nx][ny])
{
dEnd(list, nx, ny);
tab[nx][ny] = 1;
*number++;
if(!searchForMove(nx,ny,tab,list,number))
{
uEnd(list,nx,ny);
tab[nx][ny]=0;
*number--;
}
}
}
if(i == 7 && *number <64)
return 0;
if(*number == 64)
return 1;
}
Could someone show me where I made a mistake? I've checked step by step what pools algorithm is adding to list. What is big suprise algorithm after adding 4,3 pool and then 6,4 pool should call it self with 6,4 as actual position but I don't know why it's calling itself with 4,3 as actual position.

OP mostly had it. Aside from some minor code, it was the *number increment/decrement that was wrong in 2 places.
int searchForMove(int x, int y, int **tab, node **list, int *number) {
...
// *number++; // This increase the pointer to the next pointer.
(*number)++; // This dereferences number and increases it.
...
// *number--;
(*number)--; // CD
Working Example. "CD" implies my changes
// CD
#include <assert.h>
#include <inttypes.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
int mov[8][2] = { { 2, 1 }, { 2, -1 }, { -2, 1 }, { -2, -1 }, { 1, 2 },
{ -1, 2 }, { 1, -2 }, { -1, -2 } };
typedef struct element {
int x;
int y;
struct element *prev, *next;
} node;
//adding pool to list
void dEnd(node **root, int x, int y) {
node *pos;
pos = *root;
assert(pos); // CD
while (pos->next != NULL)
pos = pos->next;
pos->next = (node *) malloc(sizeof(node));
pos->next->x = x;
pos->next->y = y;
pos->next->prev = pos;
pos->next->next = NULL;
}
void uEnd(node **root, int x, int y) {
node *pos;
pos = *root;
while (pos->x != x && pos->y != y) {
pos = pos->next;
}
pos->prev->next = NULL;
free(pos);
}
void printAll(node **root) {
node *pos = *root;
unsigned i = 0; // CD
uint64_t mask = 0; // CD
while (pos->next) {
// printf("%d %d\n", pos->x, pos->y);
printf("%2u %d %d\n", i++, pos->x, pos->y); // CD prepend visit index.
mask |= 1llu << (pos->x + 8*pos->y); // CD accumulate visited squares
pos = pos->next;
}
printf("Mask %016" PRIX64 "\n", mask); // CD Show all locations visited
}
int contains(int x, int y) {
return (((x >= 0) && (x <= 7)) && ((y >= 0) && (y <= 7)));
}
//find move
int searchForMove(int x, int y, int **tab, node **list, int *number) {
int i;
for (i = 0; i < 8; i++) {
int nx, ny;
nx = x + mov[i][0];
ny = y + mov[i][1];
if (contains(nx, ny) && !tab[nx][ny]) {
dEnd(list, nx, ny);
tab[nx][ny] = 1;
// *number++;
(*number)++; // CD
if (!searchForMove(nx, ny, tab, list, number)) {
uEnd(list, nx, ny);
tab[nx][ny] = 0;
// *number--;
(*number)--; // CD
}
}
}
if (i == 7 && *number < 64)
return 0;
if (*number == 64)
return 1;
return 2; // CD added
}
// All added by CD
int main(int argc, char *argv[]) {
int tab0[8] = {0,0,0,0,0,0,0,0};
int tab1[8] = {0,0,0,0,0,0,0,0};
int tab2[8] = {0,0,0,0,0,0,0,0};
int tab3[8] = {0,0,0,0,0,0,0,0};
int tab4[8] = {0,0,0,0,0,0,0,0};
int tab5[8] = {0,0,0,0,0,0,0,0};
int tab6[8] = {0,0,0,0,0,0,0,0};
int tab7[8] = {0,0,0,0,0,0,0,0};
int *tab[8] = {tab0, tab1, tab2, tab3, tab4, tab5, tab6, tab7 };
node HeadNode = { 0, 0, NULL, NULL };
node *pHeadNode = &HeadNode;
int number = 0;
int result;
result = searchForMove(0, 0, tab, &pHeadNode, &number);
printAll(&pHeadNode);
return result;
}

Related

Binary searching in tree

I need to create this tree:
the tree
I need to implement a function that takes the tree's node (root), a number, and returns how many times the binary representation of the number occurs in the tree.
For example:
9(1001) occurs 4 times
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct TreeNode {
int val;
struct TreeNode* leftNode;
struct TreeNode* rightNode;
};
void strrev(char * arr, int start, int end) {
char temp;
if (start >= end) {
return;
}
temp = * (arr + start);
*(arr + start) = * (arr + end);
*(arr + end) = temp;
start++;
end--;
strrev(arr, start, end);
}
char * itoa(int number, char * arr, int base) {
int i = 0, r, negative = 0;
if (number == 0) {
arr[i] = '0';
arr[i + 1] = '\0';
return arr;
}
if (number < 0 && base == 10) {
number *= -1;
negative = 1;
}
while (number != 0) {
r = number % base;
arr[i] = (r > 9) ? (r - 10) + 'a' : r + '0';
i++;
number /= base;
}
if (negative) {
arr[i] = '-';
i++;
}
strrev(arr, 0, i - 1);
arr[i] = '\0';
return arr;
}
int count_occurrences(struct TreeNode* root, int number) {
int count = 0;
char binary[33];
itoa(number, binary, 2);
int length = strlen(binary);
struct TreeNode* current = root;
for (int i = 0; i < length; i++) {
if (binary[i] == '0') {
if (current->leftNode != NULL) {
current = current->leftNode;
} else {
return count;
}
} else {
if (current->rightNode != NULL) {
current = current->rightNode;
} else {
return count;
}
}
if (current->val == number) {
count++;
}
}
return count;
}
struct TreeNode* createNode(int value) {
struct TreeNode* newNode = malloc(sizeof(struct TreeNode));
newNode->val = value;
newNode->leftNode = NULL;
newNode->rightNode = NULL;
return newNode;
}
struct TreeNode* insertLeftNode(struct TreeNode* rootNode, int value) {
rootNode->leftNode = createNode(value);
return rootNode->leftNode;
}
struct TreeNode* insertRightNode(struct TreeNode* rootNode, int value) {
rootNode->rightNode = createNode(value);
return rootNode->rightNode;
}
int main() {
struct TreeNode* rootNode = createNode(1);
insertLeftNode(rootNode, 1);
insertRightNode(rootNode, 0);
insertLeftNode(rootNode->leftNode, 0);
insertRightNode(rootNode->leftNode, 1);
insertLeftNode(rootNode->rightNode, 0);
insertRightNode(rootNode->rightNode, 0);
insertLeftNode(rootNode->leftNode->leftNode, 0);
insertRightNode(rootNode->leftNode->leftNode, 0);
insertLeftNode(rootNode->rightNode->rightNode, 0);
insertRightNode(rootNode->rightNode->rightNode, 0);
printf("\n%d", count_occurrences(rootNode, 9));
}
I am using itoa(), but for some reasons it doesn't return nothing.
Itoa gave compiler warning so i copied it from internet.
Also I think i am not correctly creating the tree.

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.

How can I increment a counter in a binary search tree?

I have a list of numbers in a bst and I need to count how many times the program has the access to every single number and print it
enter
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define HASHSIZE 153
typedef struct tree
{
int key;
int count;
struct tree *dx;
struct tree *sx;
struct tree *parent;
} node;
int Insertion(node **T, node *z)
{
node* y = NULL;
node* x = *T;
// int i=1;
while ( x != NULL )
{
y = x;
if ( z->key < x->key)
{
x = x->sx;
// x->count=i; I DON'T KNOW HERE
} else if ( z->key > x->key)
{
x = x->dx;
} else
{
return -1;
}
}
z->parent = y;
if ( y == NULL ) *T = z;
if ( (y != NULL) && (z->key < y->key) ) y->sx = z;
if ( (y != NULL) && (z->key > y->key) ) y->dx = z;
return 0;
}
int main(void)
{
FILE *fp;
fp = fopen("data.txt","r");
node *x = NULL;
int search;
hashtable = (hash *) malloc(HASHSIZE * sizeof(hash));
for (i = 0; i<HASHSIZE; i++) hashtable[i].head = NULL;
while (!feof(fp))
{
fscanf(fp, "%d\t", search);
if ( Search(hashtable[H(search)].head, search)==NULL )
{
x = NewNode(search);
Insertion( &hashtable[H(x->key)].head, x);
}
}
//Here there's also the node elimination but it's not important right now
fclose(fp);
return 0;
}
My problem is printing the number of times that a number compare in a file.
I put down there NewNode, Search and H function
// HASH //
typedef struct _hash
{
node *head;
} hash;
hash *hashtable = NULL;
int H(int key)
{
return (key % HASHSIZE);
}
// NEWNODE //
node* NewNode(int z)
{
node* temp;
temp = (node*) malloc( sizeof(node) );
temp->key = z;
temp->sx = NULL;
temp->dx = NULL;
temp->parent = NULL;
return temp;
}
// SEARCH //
node* Search(node *x, int k)
{
while ( (x != NULL) && (k != x->key) )
{
if ( k < x->key )
{
x = x->sx;
}
else
{
x = x->dx;
}
}
return x;
}
// TOP //
int Top(int a, int b)
{
if (a>b) return a;
return b;
}
// MIN //
node* Min(node *x)
{
while (x->sx != NULL) x = x->sx;
return x;
}
// MAX //
node* Max(node *x)
{
while (x->dx != NULL) x = x->dx;
return x;
}
// NEXT //
node* Next(node *x)
{
if (x->dx != NULL)
return Min(x->dx);
node *y = x->parent;
while ( y != NULL && x == y->dx ){
x = y;
y = y->parent;
}
return y;
}
// HEIGHT //
int Height(node *x)
{
if (x == NULL)
return 0;
return( 1 + Top( Height(x->sx), Height(x->dx) ));
}
// DECANT //
void Decant(node **T, node *u, node *v)
{
if ( u->parent == NULL)
*T = v;
if ( u->parent != NULL && u == u->parent->sx )
u->parent->sx = v;
if ( u->parent != NULL && u == u->parent->dx )
u->parent->dx = v;
if ( v != NULL)
v->parent = u->parent;
}
// DELATE //
void Delate(node **T, node *z)
{
node *y;
if ( z->sx == NULL )
Decant(T, z, z->dx);
if ( (z->sx != NULL) && (z->dx == NULL) )
Decant(T, z, z->sx);
if ( (z->sx != NULL) && (z->dx != NULL) )
{
y = Min(z->dx);
if (y->parent != z){
Decant(T, y, y->dx);
y->dx = z->dx;
y->dx->parent = y;
}
Decant(T, z, y);
y->sx = z->sx;
y->sx->parent = y;
}
free(z);
}
Thx everyone!

XOR maximization using a trie

I am trying to solve this question-
Given an array A of unsigned 32-bit ints, choose two in-bounds indices i, j so as to maximize the value of A[i] ^ A[j], where ^ is the bitwise XOR (exclusive OR) operator.
Example Input:
4 2 0 13 49
Output:
60
Explanation: 13 ^ 49 is 60
Here is my code
#include <stdio.h>
void insert(int n, int pos, struct node *t);
int find(struct node *p1, struct node *p2);
struct node *alloc();
struct node{
int value;
struct node *left;
struct node *right;
};
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
int n;
scanf("%d", &n);
struct node root;
root.value = 0;
root.left = root.right = NULL;
while (n--)
{
int num;
scanf("%d", &num);
insert(num, 31 , &root);
}
int max = find(&root, &root);
printf("%d\n", max);
}
return 0;
}
void insert(int n, int pos, struct node *t)
{
if (pos >= 0)
{
struct node *m;
int bit = (1 << pos)&n;
if (bit)
{
if (t->right == NULL)
{
m=alloc();
m->value = 1;
m->left = NULL;
m->right = NULL;
t->right = m;
}
if (pos == 0)
{
m=alloc();
m->value = n;
m->left = NULL;
m->right = NULL;
t->left = m;
}
insert(n, pos - 1, t->right);
}
else
{
if (t->left == NULL)
{
m = alloc();
m->value = 0;
m->left = NULL;
m->right = NULL;
t->left = m;
}
if (pos == 0)
{
m=alloc();
m->value = n;
m->left = NULL;
m->right = NULL;
t->left = m;
}
insert(n, pos - 1, t->left);
}
}
}
int find(struct node *p1, struct node *p2)
{
if ((p1->left != NULL) ||(p1->right != NULL))
{
int n01 = 0;
int n10 = 0;
if (p1->left != NULL && p2->right != NULL)
{
n01 = find(p1->left, p2->right);
}
if ((p1->right != NULL) && (p2->left != NULL))
{
n10 = find(p2->left, p1->right);
}
else
{
if (p1->left!=NULL && p2->left!=NULL)
n01 = find(p1->left, p2->left);
else
n10 = find(p1->right, p2->right);
}
return (n01 > n10 ? n01 : n10);
}
else
{
return p1->value^p2->value;
}
}
struct node *alloc()
{
return (struct node *) malloc(sizeof(struct node));
}
I am only getting a 0 as output.I know there are mistakes in my code.Please help me in finding the mistakes or if necessary the right solution.

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