0

I'm trying to make the n queen problem in C, but with dynamic allocation and getting data from files.

so I found this code:

/* C/C++ program to solve N Queen Problem using
backtracking */
#include<bits/stdc++.h>
#define N 4

/* A utility function to print solution */
void printSolution(int board[N][N])
{
    static int k = 1;
    printf("%d-\n",k++);
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N; j++)
            printf(" %d ", board[i][j]);
        printf("\n");
    }
    printf("\n");
}

/* A utility function to check if a queen can
be placed on board[row][col]. Note that this
function is called when "col" queens are
already placed in columns from 0 to col -1.
So we need to check only left side for
attacking queens */
bool isSafe(int board[N][N], int row, int col)
{
    int i, j;

    /* Check this row on left side */
    for (i = 0; i < col; i++)
        if (board[row][i])
            return false;

    /* Check upper diagonal on left side */
    for (i=row, j=col; i>=0 && j>=0; i--, j--)
        if (board[i][j])
            return false;

    /* Check lower diagonal on left side */
    for (i=row, j=col; j>=0 && i<N; i++, j--)
        if (board[i][j])
            return false;

    return true;
}

/* A recursive utility function to solve N
Queen problem */
bool solveNQUtil(int board[N][N], int col)
{
    /* base case: If all queens are placed
    then return true */
    if (col == N)
    {
        printSolution(board);
        return true;
    }

    /* Consider this column and try placing
    this queen in all rows one by one */
    bool res = false;
    for (int i = 0; i < N; i++)
    {
        /* Check if queen can be placed on
        board[i][col] */
        if ( isSafe(board, i, col) )
        {
            /* Place this queen in board[i][col] */
            board[i][col] = 1;

            // Make result true if any placement
            // is possible
            res = solveNQUtil(board, col + 1) || res;

            /* If placing queen in board[i][col]
            doesn't lead to a solution, then
            remove queen from board[i][col] */
            board[i][col] = 0; // BACKTRACK
        }
    }

    /* If queen can not be place in any row in
        this column col then return false */
    return res;
}

/* This function solves the N Queen problem using
Backtracking. It mainly uses solveNQUtil() to
solve the problem. It returns false if queens
cannot be placed, otherwise return true and
prints placement of queens in the form of 1s.
Please note that there may be more than one
solutions, this function prints one of the
feasible solutions.*/
void solveNQ()
{
    int board[N][N];
    memset(board, 0, sizeof(board));

    if (solveNQUtil(board, 0) == false)
    {
        printf("Solution does not exist");
        return ;
    }

    return ;
}

// driver program to test above function
int main()
{
    solveNQ();
    return 0;
}

but I have no idea how to transform that #define N to getting the N from a .txt file and is that a dynamic allocation? (with memset, sizeof? ) I'm newbie when coming to C/C++, if anyone can help me out here?

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
themarksmaker
  • 61
  • 2
  • 10
  • Possible duplicate of [How to read / parse input in C? The FAQ](https://stackoverflow.com/questions/35178520/how-to-read-parse-input-in-c-the-faq) – Yunnosch May 06 '18 at 19:44
  • 1
    Please read [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) Which is a **C++** header by the way. And remember, there's no such language as "C/C++". There is *either* C *or* C++, and they are two *very* different languages. – Some programmer dude May 06 '18 at 19:50
  • @Yunnosch no, it isn't. It's about how to implement the code when you have `int N = 4;` – Weather Vane May 06 '18 at 20:27
  • I want to replace #define N to a variable N that will be taken from a text file. – themarksmaker May 06 '18 at 20:28
  • @Yunnosch you haven't understood the question: OP's comments confirm what I say (and below the first answer), which is how to implement `int N = 4;` instead of `#define N 4`. – Weather Vane May 06 '18 at 20:31
  • @themarksmaker is your problem reading a number from a text file, or implementing `int N = 4;` instead of `#define N 4`? Please be clear. – Weather Vane May 06 '18 at 20:35
  • @Yunnosch at the bottom of the question is "I have no idea how to transform that #define N to getting the N from a .txt file". So even if `N` was obtained as a variable, the problem of implementing that in the Queen problem remains. OP also asked "is that a dynamic allocation? (with memset, sizeof? ) ". I would have thought that a commenter of your calibre would have understood the question. – Weather Vane May 06 '18 at 20:53
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/170487/discussion-between-yunnosch-and-weather-vane). – Yunnosch May 06 '18 at 21:24

1 Answers1

2

Here is an example of how to change the N with a number read from a text file. You can run the program with any number you like now.

If you read from file, the file must have been created and called "myFile.txt", you can read only 1 integer from it.

You can remove the lines in main() that read the number from a file, and instead declare int number = 4 for example.

I have tested it with 4. It's up to you to further optimize this code. It's very raw version for start.

#include <stdio.h>
#include <stdlib.h>

#define true    1
#define false   0

void destroyBoard(int **board, int number)
{
for (int i = 0; i < number; ++i)
    free(board[i]);

free(board);
}
/* A utility function to print solution */
void printSolution(int **board, int number)
{
static int k = 1;
printf("%d-\n",k++);
for (int i = 0; i < number; i++)
{
    for (int j = 0; j < number; j++)
        printf(" %d ", board[i][j]);
    printf("\n");
}
printf("\n");
}

/* A utility function to check if a queen can
be placed on board[row][col]. Note that this
function is called when "col" queens are
already placed in columns from 0 to col -1.
So we need to check only left side for
attacking queens */
int isSafe(int **board, int row, int col, int number)
{
int i, j;

/* Check this row on left side */
for (i = 0; i < col; i++)
    if (board[row][i])
        return false;

/* Check upper diagonal on left side */
for (i=row, j=col; i>=0 && j>=0; i--, j--)
    if (board[i][j])
        return false;

/* Check lower diagonal on left side */
for (i=row, j=col; j>=0 && i<number; i++, j--)
    if (board[i][j])
        return false;

return true;
}

/* A recursive utility function to solve N
Queen problem */
int solveNQUtil(int **board, int col, int number)
{
/* base case: If all queens are placed
then return true */
if (col == number)
{
    printSolution(board, number);
    return true;
}

/* Consider this column and try placing
this queen in all rows one by one */
int res = false;
for (int i = 0; i < number; i++)
{
    /* Check if queen can be placed on
    board[i][col] */
    if ( isSafe(board, i, col, number) )
    {
        /* Place this queen in board[i][col] */
        board[i][col] = 1;

        // Make result true if any placement
        // is possible
        res = solveNQUtil(board, col + 1, number) || res;

        /* If placing queen in board[i][col]
        doesn't lead to a solution, then
        remove queen from board[i][col] */
        board[i][col] = 0; // BACKTRACK
    }
}

/* If queen can not be place in any row in
    this column col then return false */
return res;
}

/* This function solves the N Queen problem using
Backtracking. It mainly uses solveNQUtil() to
solve the problem. It returns false if queens
cannot be placed, otherwise return true and
prints placement of queens in the form of 1s.
Please note that there may be more than one
solutions, this function prints one of the
feasible solutions.*/
void solveNQ(int number)
{
int **board = malloc(number * sizeof(*board));
if (board == NULL)
{
    return;
}

for (int i = 0; i < number; ++i)
{
    board[i] = malloc(number * sizeof(**board));
    if (board[i] == NULL)
    {
        destroyBoard(board, i);
        return;
    }
}

for (int i = 0; i < number; ++i)
    for (int j = 0; j < number; ++j)
         board[i][j] = 0;


if (solveNQUtil(board, 0, number) == false)
{
    printf("Solution does not exist");
}

destroyBoard(board, number);

return ;
}

// driver program to test above function
int main(void)
{
int number = 0;
FILE *fp = NULL;

if ( (fp  = fopen("myFile.txt", "r")) == NULL)
{
    printf("Error opening file!\n");

    return -1;
}

fscanf(fp, "%d", &number);

printf("number: %d\n", number);

solveNQ(number);

fclose(fp);

return 0;
}
  • I think the question was about how to convert the code from using `#define N 4` to using a variable obtained from somewhere to set the board size - not how to obtain that variable. So how to write the code when instead of the `#define` there is global (or even local) `int N = 4;` – Weather Vane May 06 '18 at 20:20
  • The question was how to obtain the `N` from a text file, so I showed a basic example of how to read a number from a text file. He can easily substitute this in his code and read the 'N` from a text file. – малин чекуров May 06 '18 at 20:22
  • Please read the question more carefully. The code posted used `#define N 4`. Reading a text file or simply defining `int N = 4;` is trivial. The question is about how to implement that variable in the board. – Weather Vane May 06 '18 at 20:23
  • Edited the answer, now the queen program can work with any number read from text file and dynamic allocates the data. – малин чекуров May 06 '18 at 21:09
  • Yea, exactly what I wanted..thanks a lot mate!! @малинчекуров – themarksmaker May 07 '18 at 13:29