I am trying to solve the n-queen problem on leetcode. But it is giving heap overflow error on leetcode.
But on my computer when I give single input it give correct answer but on giving input multiple times it gives segmentation fault: 11 error.
And when I don't print the complete chess board. Just printing the number of different possible solution. Then also it works fine.
#include <stdio.h>
#include <stdlib.h>
#define bool int
#define true 1
#define false 0
//checking positioned queens
bool checkPlacedQueens(char **board, int queeni, int queenj, int n) {
int i=queeni;
int j=queenj;
//checking complete row
for(int i=queeni; i>=0; i--) {
if(board[i][j] == 'Q')
return false;
}
i=queeni;
j=queenj-1;
//checking left diagonal
while(i>=0 && j>=0) {
if(board[i--][j--] == 'Q')
return false;
}
i=queeni;
j=queenj+1;
//checking right diagonal
while(i>=0 && j<=n) {
if(board[i--][j++] == 'Q')
return false;
}
return true;
}
char ***placeQueens(char **board, int queenI, int n, int *returnSize, char ****result) {
//all queens are on their correct position
if(queenI == n) {
(*returnSize)++;
/*
reallocating the memory to save all the outputs in 3D
array
*/
(*result) = (char ***) realloc(*result, sizeof(char **)*(*returnSize));
(*result)[*returnSize-1] = (char **)malloc(sizeof(char *)*n);
for(int i=0; i<n; i++) {
(*result)[*returnSize-1][i] = (char *)malloc(sizeof(char)*n);
}
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
(*result)[*returnSize-1][i][j] = board[i][j];
}
}
return *result;
}//if
for(int j=0; j<n; ++j) {
char save = board[queenI][j];
board[queenI][j] = 'Q';
if(checkPlacedQueens(board, queenI-1, j, n)) {
placeQueens(board, queenI+1, n, returnSize, result);
}
board[queenI][j] = save;
}//for Loop
return *result;
}//function
char *** solveNQueens(int n, int* returnSize) {
char **board;
char ***result = (char ***)malloc(sizeof(char **));
board = (char **)malloc(sizeof(char *)*n);
for(int i=0; i<n; i++) {
board[i] = (char *)malloc(sizeof(char)*n);
}
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
board[i][j] = '.';
}
}
placeQueens(board, 0, n, returnSize, &result);
for(int i=0; i<n; i++)
free(board[i]);
free(board);
return result;
}//char
int main(void) {
int returnSize=0;
int n=4;
char ***arr;
while(n<10) {
arr = solveNQueens(n, &returnSize);
for(int i=0; i<returnSize; ++i) {
for(int j=0; j<n; j++) {
for(int k=0; k<n; k++) {
printf("%c", arr[i][j][k]);
}
printf("\n");
}
printf("\n");
}
printf("\n\n\n");
for(int i=0; i<returnSize; ++i) {
for(int j=0; j<n; j++) {
free(arr[i][j]);
}
free(arr[i]);
}
free(arr);
arr=NULL;
n++;
}
}//main
Yoor code has an out-of-bounds read illegal memory access. A live test of it is here segfault diagnoser,
The following is the diagnostic message of the out-of-bounds read.
====== Start of Stensal DTS message == (56.133) == copy start here ======
[out-of-bounds read] is detected by Stensal DTS.
Continuing execution can cause undefined behavior, abort!
+--------------------------------------------------------------------------+
| Reading 1 bytes from 0x80c5054 will read undefined values.
|
| The object to-be-read (start:0x80c5050, size:4 bytes) is allocated at
| file:/prog.c::83, 28
|
| 0x80c5050 0x80c5053
| +------------------------+
| | the object to-be-read |......
| +------------------------+
| ^~~~~~~~~~
| the read starts at 0x80c5054 that is right after the object end.
|
| Stack trace (most recent call first) of the read.
| [1] file:/prog.c::31, 12
| [2] file:/prog.c::67, 12
| [3] file:/prog.c::68, 13
| [4] file:/prog.c::92, 5
| [5] file:/prog.c::107, 15
| [6] [libc-start-main]
+--------------------------------------------------------------------------+
======= End of Stensal DTS message =============== copy end here =========
The problem is that your are not resetting the value of returnSize each time you re-call the solveNQueens function.
The following is a working code:
#include <stdio.h>
#include <stdlib.h>
#define bool int
#define true 1
#define false 0
//checking positioned queens
bool checkPlacedQueens(char **board, int queeni, int queenj, int n) {
int i=queeni;
int j=queenj;
//checking complete row
for(int i=queeni; i>=0; i--) {
if(board[i][j] == 'Q')
return false;
}
i=queeni;
j=queenj-1;
//checking left diagonal
while(i>=0 && j>=0) {
if(board[i--][j--] == 'Q')
return false;
}
i=queeni;
j=queenj+1;
//checking right diagonal
while(i>=0 && j<=n) {
if(board[i--][j++] == 'Q')
return false;
}
return true;
}
char ***placeQueens(char **board, int queenI, int n, int *returnSize, char ****result) {
//all queens are on their correct position
if(queenI == n) {
(*returnSize)++;
/*
reallocating the memory to save all the outputs in 3D
array
*/
(*result) = (char ***) realloc(*result, sizeof(char **)*(*returnSize));
(*result)[*returnSize-1] = (char **)malloc(sizeof(char *)*n);
for(int i=0; i<n; i++) {
(*result)[*returnSize-1][i] = (char *)malloc(sizeof(char)*n);
}
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
(*result)[*returnSize-1][i][j] = board[i][j];
}
}
return *result;
}//if
for(int j=0; j<n; ++j) {
char save = board[queenI][j];
board[queenI][j] = 'Q';
if(checkPlacedQueens(board, queenI-1, j, n)) {
placeQueens(board, queenI+1, n, returnSize, result);
}
board[queenI][j] = save;
}//for Loop
return *result;
}//function
char *** solveNQueens(int n, int* returnSize) {
char **board;
char ***result = (char ***)malloc(sizeof(char **));
board = (char **)malloc(sizeof(char *)*n);
for(int i=0; i<n; i++) {
board[i] = (char *)malloc(sizeof(char)*n);
}
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
board[i][j] = '.';
}
}
placeQueens(board, 0, n, returnSize, &result);
for(int i=0; i<n; i++)
free(board[i]);
free(board);
return result;
}//char
int main(void) {
int n=4;
char ***arr;
while(n<10) {
// Reset the value of returnSize
int returnSize=0;
arr = solveNQueens(n, &returnSize);
for(int i=0; i<returnSize; ++i) {
for(int j=0; j<n; j++) {
for(int k=0; k<n; k++) {
printf("%c", arr[i][j][k]);
}
printf("\n");
}
printf("\n");
}
printf("\n\n\n");
for(int i=0; i<returnSize; ++i) {
for(int j=0; j<n; j++) {
free(arr[i][j]);
}
free(arr[i]);
}
free(arr);
arr=NULL;
n++;
}
}//main
Related
At the moment I am creating a program where the user is asked to place the queens for the 8 Queens Problem. Right now I have nearly created the program, but I'm stuck on how to make the program check diagonally.
This is the (unfinished)code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int check_r_c(int**chess,int*p,int N,int M)
{
int times=0;
for(int i=0; i<N; i++)
{
times=0;
for(int j=0; j<M; j++)
{
if(chess[i][j] == 1)
times++;
}
if( times != 1)
{
*p=1;
return 1;
}
}
for(int j=0; j<M; j++)
{
times=0;
for(int i=0; i<N; i++)
{
if(chess[i][j] == 1)
times++;
}
if( times != 1)
{
*p=1;
return 1;
}
}
*p=0;
return 0;
}
int main()
{
int N,M;
printf("Give the number of rows: \n");
scanf("%d",&N);
printf("Give the number of columns: \n");
scanf("%d",&M);
int**chess = malloc(N*sizeof(int));
int i,j,ch;
int*ptr;
ptr=&ch;
if(chess==NULL)
{
printf("\nMemory cannot be allocated\n");
return 1;
}
for(i=0; i<N; i++)
{
if((chess[i] = malloc(M*sizeof(int)))==NULL)
{
printf("\nMemory cannot be allocated\n");
return 1;
}
}
for(int i=0; i<N; i++)
for(int j=0; j<M; j++)
chess[i][j]= 0;
for(int k=0; k<N; k++)
{
printf("Give the position of the %d queen\n",k+1);
scanf("%d",&i);
scanf("%d",&j);
if(chess[i][j] == 1)
{
printf("You cant put 2 queens in the same place!!!\n" );
return 0;
}
chess[i][j] = 1;
}
check_r_c(chess,ptr,N,M);
if(ch == 0)
printf("Solution is correct!");
else
printf("Solution is incorrect!");
for(int i=0; i<N; i++)
free(chess[i]);
free(chess);
}
The logic for checking diagonal for a queen placed is (p,q) is to check for all the places located at (p+i,q+i) for all i, where both p+i and q+i are within the board. For negative side, use (p-i,q-i).
I'm doing a challenge on HackerRank got the method figured out but there's a slight error I cannot figure out. Further information if needed is https://www.hackerrank.com/challenges/sparse-arrays
Basically I only have a problem with arr[0]. It's storing arr[0] as 'aba', then once it hits the first for loop it changes to 'ab'. Why?
Input:
4
aba
baba
aba
xzxb
3
aba
xzxb
ab
Code:
int main() {
int i, j;
int n;
int q;
scanf("%d", &n);
char* arr[n];
char* test[q];
char* s;
int counter[q];
for (i = 0; i < q; i++) {
counter[i] = 0;
}
for (i = 0; i < n; i++) {
arr[i] = malloc(20);
scanf("%s", arr[i]);
}
scanf("%d", &q);
for (i = 0; i < q; i++) {
test[i] = malloc(20);
scanf("%s", test[i]);
}
for (i = 0; i < n; i++) {
for (j = 0; j < q; j++) {
if (strcmp(arr[i], test[j]) == 0) {
counter[j]++;
} else {
}
}
}
for (i = 0; i < q; i++) {
printf("%d\n", counter[i]);
}
return 0;
}
You declared test and counter as array of size q before having initialize q. Move there declaration just after scanf("%d",&q);. Also move the initializing loop of counter :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int i, j;
int n;
int q;
scanf("%d", &n);
char* arr[n];
char* s;
for(i=0; i<n; i++) {
arr[i]= malloc(20);
scanf("%s",arr[i]);
}
scanf("%d", &q);
int counter[q];
char* test[q];
for(i=0; i<q; i++) {
counter[i] = 0;
}
for(i=0; i<q; i++) {
test[i]= malloc(20);
scanf("%s",test[i]);
}
for(i=0; i<n; i++) {
for(j=0; j<q; j++) {
if (strcmp(arr[i],test[j]) == 0) {
counter[j]++;
}
}
}
for(i=0; i<q; i++) {
printf("%d\n", counter[i]);
}
return 0;
}
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int i, j;
int n;
int q;
scanf("%d", &n);
char* arr[n];
for (i = 0; i < n; i++) {
arr[i] = malloc(20);
scanf("%s", arr[i]);
}
scanf("%d", &q);
char* test[q];
char* s;
int counter[q];
for (i = 0; i < q; i++) {
counter[i] = 0;
}
for (i = 0; i < q; i++) {
test[i] = malloc(20);
scanf("%s", test[i]);
}
for (i = 0; i < n; i++) {
for (j = 0; j < q; j++) {
if (strcmp(arr[i], test[j]) == 0) {
counter[j]++;
} else {
}
}
}
for (i = 0; i < q; i++) {
printf("%d\n", counter[i]);
}
return 0;
}
try this, use varialble after declaration and initialization
I am trying to build a dynamic maze i got to the part where i get the size and get the chars that i need to build the maze from them.
but the function thats build the maze prints it really asymmetrical how can i fix that?
my code:
#include <stdio.h>
#include <stdlib.h>
char **board;
int size = 0;
void print_Board();
void initialize_Board();
int main()
{
initialize_Board();
print_Board();
return 0;
}
/*initialize the board*/
void initialize_Board()
{
int i, j;//indexs
char s;
scanf("%d", &size);
board = (char**)malloc(sizeof(char*)* (size));
if (!board) { printf("ERROR - memroy allocation.\n"); exit(1); }
for (i = 0; i < size; i++)//for loops to build the board for the game
{
board[i] = (char*)malloc(sizeof(char)*(size));
if (!board[i]) { printf("ERROR - memroy allocation, for loop\n");
exit(1);
}
for (j = 0; j < size; j++)
{
scanf("%c", &s);
board[i][j] = s;
}//for col
printf("\n");
}//for row
}
//print the board
void print_Board()
{
int i, j;
for (i = 0; i < size; i++)
{
for (j = 0; j < size; j++)
{
printf("%c ", board[i][j]); //print the value in the [i][j] place.
}//for col
printf("\n");
}//for row
}
Change:
for (j = 0; j < size; j++)
{
scanf("%c", &s);
board[i][j] = s;
}//for col
To:
for (j = 0; j < size; j++) {
scanf("%c ", &s);
board[i][j] = s;
}//for col
board[i][j] = '\n'; // Add new line to end of row making it a string.
This ensures that each character is read and the return char is discarded.
and change:
int i, j;
for (i = 0; i < size; i++)
{
for (j = 0; j < size; j++)
{
printf("%c ", board[i][j]); //print the value in the [i][j] place.
}//for col
printf("\n");
}//for row
to:
int i;
for (i = 0; i < size; i++) {
printf("%s", board[i]); //print the values in the [i] row.
}
This prints each row with a newline at the end.
with first function i fill 5x5 array with 0 (means that users aren't friends, or 1 that mean they are friends.
second function calculate friends of each user.
third function calculate and return common friends between users.
and i have problem with last fucntion, it have to calculate friends of each user and save it in 1D array, and then bubble short the array.
can anyone help me to find out what is wrong with the last function
friendship array is
01100
10111
11010
01100
01000
Code
#include <stdio.h>
#include <stdlib.h>
/* function declaration */
void loadMatrix (int **F, int size);
int findFriends (int **F, int size, int user);
int commonFriends (int **F, int size, int user1, int user2);
void sortUsers (int **F, int size, int *S);
int main()
{
int **matrixF; /* friendship array */
int *matrixS; /* sum of each user array */
int num_users; /* users number */
int i, j;
printf("Give number of users: ");
scanf("%d", &num_users);
/* allocate memory for array */
matrixF = (int **) malloc(num_users * sizeof(int *));
if (!matrixF)
{
printf("Memory allocation error!\n");
exit(1);
}
for (i = 0; i < num_users; ++i)
{
matrixF[i] = (int *) malloc(num_users * sizeof(int));
if (!matrixF[i])
{
printf("Memory allocation error!\n");
exit(1);
}
}
loadMatrix(matrixF, num_users);
for (i=0; i<num_users; ++i)
{
printf("Number of friends of user %d: %d\n", i, findFriends(matrixF, num_users, i));
}
/* common friends */
for (i=0; i<num_users; ++i)
{
for (j=0; j<i; ++j)
{
printf("Number of common friends of %d and %d: %d\n", i, j, commonFriends(matrixF, num_users, i, j));
}
}
matrixS = (int *)malloc(num_users * sizeof(int));
if (!matrixS)
{
printf("Memory allocation error!\n");
exit(1);
}
sortUsers(matrixF, num_users, matrixS);
/* bubble short */
for (i=0; i<num_users; ++i)
{
printf("%d friends.\n", matrixS[i]);
}
return 0;
}
void loadMatrix (int **F, int size)
{
int i, j;
for (i=0; i<size; i++)
for (j=0; j<size; j++)
{
do
{
printf(" user%d is friend with user%d: ", i, j);
scanf("%d", &F[i][j]);
if ((F[i][j]<0) || (F[i][j]>1 )) printf("H timi prepei einai 0 i 1 . ");
}
while ((F[i][j]<0) || (F[i][j]>1)); /*please enter 0 or 1*/
}
}
int findFriends (int **F, int size, int user) {
int j;
int sum=0;
for(j=0; j<size; j++)
{
sum+=F[user][j];
}
return (sum);
}
int commonFriends (int **F, int size, int user1, int user2) {
int j;
int counter=0;
for (j=0; j<size; j++)
{
if ((F[user1][j]==1)&&(F[user2][j]==1))
counter++;
}
return (counter);
system("pause");
}
void sortUsers (int **F, int size, int *S)
{
int i, j, temp;
int sum=0;
for(i=0; i<size; i++)
{
for(j=0; j<size; j++)
sum+=F[i][j];
}
S[i]=sum;
printf("%d\t", S[i]);
for(i=0; i<size; i++)
{
S[i]=sum;
}
for (i=1; i<size; i++)
{
for (j=0; j<size-1; j++)
{
if (S[j]>S[j+1])
{
temp = S[j];
S[j] = S[j+1];
S[j+1] = temp;
}
}
}
}
i just find out the answer
void sortUsers (int **F, int size, int *S) {
int i, j, temp, user;
int sum;
for (i=0; i<size; i++){
sum=0;
for (j=0; j<size; j++)
S[i]=(sum+=F[i][j]);
}
for (i=0; i<size; i++)
printf("%d\t", S[i]);
for (i=1; i<size; i++) {
for (j=0; j<size-1; j++) {
if (S[j]>S[j+1]) {
temp = S[j];
S[j] = S[j+1];
S[j+1] = temp;
}
}
}
system("pause");
}
I'm very new to this and to C programming. It's my first year and things are not very clear for me. Hopefully I can get better very soon.
I have a code here where i input a number and I get results based on the table I have below.
I would like to know: If i have a given string (in the code it's: test[7]="2 B 1 C")
How can I compare the result i have to this string and see if it's the same to print=good?
it's very hard to explain so please let me know if i'm not clear with my question. You can test the code to see how it works.
#include <stdio.h>
#include <string.h>
void initialize(int poss[1296][4]);
int main()
{
int table[1296][4];
char str[5];
char tmp[5];
int i, j, k;
int bull = 0;
int cow = 0;
char test[7]={"2 B 0 C"};
initialize(table);
printf("Enter 4 digits: ");
scanf("%s", str);
for (i=0; i<1296; i++) // building this table
{
strcpy(tmp, str); // copying string
for (j=0; j<4; j++)
{
for (k=0; k<4; k++)
{
if (table[i][j]==tmp[k]-'0' && j==k) // gets the string as an integer
{
tmp[k] = -1;
bull++;
break;
}
else if (table[i][j]==tmp[k]-'0' && j!=k)
{
tmp[k] = -1;
cow++;
break;
}
}
}
printf ("%d B %d C\n\n", bull, cow);
bull = 0;
cow = 0;
}
}
//------------------------------------TABLE---------------------------------//
void initialize(int poss[1296][4])
{
int i=0;
int j, k=0;
int m;
while (i<=5)
{
for (j=0; j<216 ; j++)
{
poss[k][0]=i;
k++;
}
i++;
}
k=0;
i=0;
j=0;
while (k<1296)
{
for (m=0; m<6; m++)
{
for (j=0; j<6; j++)
{
for (i=0; i<36 ; i++)
{
poss[k][1]=j;
k++;
}
}
}
}
k=0;
i=0;
j=0;
m=0;
while (k<1296)
{
for (j=0; j<6; j++)
{
for (i=0; i<6; i++)
{
poss[k][2]=j;
k++;
}
}
}
k=0;
i=0;
j=0;
m=0;
while (k<1296)
{
for (i=0; i<6; i++)
{
poss[k][3]=i;
k++;
}
}
}
You can use sprintf to generate the result into a string instead of printing it, then use strcmp to compare that string to what you expect it to be. You can also then use printf to print the string you produced with sprintf. (When you sprintf, don't include the newlines since those aren't in your test string; only output those with printf).
What's not clear from your question, however, is that you only have one test string but print 1296 lines ... if those lines aren't all the same then you need an array of 1296 test results ... or a clearer question.
sample
#include <stdio.h>
#include <string.h>
int main(){
char test[8]={"2 B 0 C"};
char result[8];
int bull = 0;
int cow = 0;
bull = 2;//set by program
cow = 0;
sprintf(result, "%d B %d C", bull, cow);
if(strcmp(result, test)==0){
printf("match!\n");
} else {
printf("not match!\n");
}
return 0;
}