Question

Can someone please complete the "allTheQueensAreSafe" function? #include <stdio.h> #include <stdlib.h> void printBoard(int *whichRow, int n)...

Can someone please complete the "allTheQueensAreSafe" function?

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

void printBoard(int *whichRow, int n)
{
   int row, col;

   for (row = 0; row < n; row++)
   {
       for (col = 0; col < n; col++)
       {
           printf("%c", (whichRow[col] == row) ? 'Q' : '.');
       }
       printf("\n");
   }

   printf("\n");
}

int allTheQueensAreSafe(int *whichRow, int n, int currentCol)
{
   // TODO: Write a function that returns 1 if all the queens represented by
   // this array are safe (i.e., none of them can attack one another).
   // Otherwise, return 0. For an explanation of these parameters, see the
   // backtrack() and nqueens() functions below.
}

int backtrack(int *whichRow, int n, int col)
{
   int row, total = 0;

   // Base case. If we get to a point where col == n, that means we've
   // successfully thrown down n queens. We print the solution and return 1 to
   // indicate that we have found 1 solution at the end of this branch.
   if (col == n)
   {
       printBoard(whichRow, n);
       return 1;
   }

   // Note: Typically, we would also check to be sure that this state is not
   // one we have seen before, and if it were, we would return immediately.
   // However, the process I'm using below to generate new states never has the
   // ability to generate the same state more than once, so we don't need to
   // check for that here.

   // Now we generate all possible branches by attemping to place the queen in
   // each row for this particular column.
   for (row = 0; row < n; row++)
   {
       // Make a move. (Place the queen at this particular row.)
       whichRow[col] = row;

       // Make a recursive call. Note that we only make this recursive call if
       // none of the queens can attack one another. In backtracking, we never
       // explore branches that we know to be infeasible. (This call to
       // allTheQueensAreSafe() does not have to be done here, though. It could
       // instead be used in an additional base case where we return
       // immediately if not all the queens are safe.)
       if (allTheQueensAreSafe(whichRow, n, col))
           total += backtrack(whichRow, n, col + 1);

       // At this point, we would typically undo the move we made above (the
       // state change that took place before the recursive call). However, in
       // this case, that will be undone in the next iteration of the for-loop,
       // so there's nothing for us to explicitly undo here.
   }

   // We've been keeping track of how many solutions were discovered along the
   // many recursive branches we explored. Let's now return that total.
   return total;
}

int nqueens(int n)
{
   // The whichRow array will indicate the row in which a queen is placed for
   // each column. The column serves as an index to the array, and the value at
   // that position tells us the row where the queen is located for that
   // column.
   //
   // For example, consider the following 4x4 board with 4 queens:
   //
   // ..Q.
   // Q...
   // ...Q
   // .Q..
   //
   // The queen in column 0 is in row 1.
   // The queen in column 1 is in row 3.
   // The queen in column 2 is in row 0.
   // The queen in column 3 is in row 2.
   //
   // Thus, our array would look like this: {1, 3, 0, 2}

   int *whichRow = malloc(sizeof(int) * n);
   return backtrack(whichRow, n, 0);

   // WARNING: This has a memory leak. (lol)
}

int main(int argc, char **argv)
{
   if (argc < 2)
   {
       fprintf(stderr, "Proper syntax: %s <n>\n", argv[0]);
       exit(1);
   }

   printf("%d\n", nqueens(atoi(argv[1])));
   return 0;
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

This is the function that returns whether the queen is attacked or not . if it returns 1 that means queen is in danger 0 means it is not in danger .


//function to check if the cell is attacked or not

int is_attack(int i,int j)

{

    int k,l;

    //checking if there is a queen in row or column

    for(k=0;k<N;k++)

    {

        if((board[i][k] == 1) || (board[k][j] == 1))//if queen present then yes there is danger

            return 1;

    }

    //check for diagonals

    for(k=0;k<N;k++)

    {

        for(l=0;l<N;l++)

        {

            if(((k+l) == (i+j)) || ((k-l) == (i-j)))

            {

                if(board[k][l] == 1)

                    return 1;

            }

        }

    }

    return 0;

}

Add a comment
Know the answer?
Add Answer to:
Can someone please complete the "allTheQueensAreSafe" function? #include <stdio.h> #include <stdlib.h> void printBoard(int *whichRow, int n)...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • #include <stdio.h> #include <stdlib.h> #define TOTAL_ROWS 15 int main() { int row, col, numstars=1; int half,...

    #include <stdio.h> #include <stdlib.h> #define TOTAL_ROWS 15 int main() { int row, col, numstars=1; int half, rate = 1; // Loop through each row. for (row=1; row<=TOTAL_ROWS; row++) { half= TOTAL_ROWS/2; // Draw the blanks before the stars for (col=0; col< half + 1 -numstars; col++) printf(" "); // Draw the stars for (col=1; col<= 2*numstars - 1; col++) printf("*"); // If we hit the middle of the diamond, negate the rate. if ((numstars == (half + 1))) rate =...

  • Read the following code, threaded recursive calculation of Fibonacci number of n: #include <stdio.h> #include <stdlib.h>...

    Read the following code, threaded recursive calculation of Fibonacci number of n: #include <stdio.h> #include <stdlib.h> #include <pthread.h> void *fib(void *arg); int main(int argc, char **argv){     int n = atoi(argv[1]);     printf("%d\n", (int)fib(n)); } void *fib(void *arg){     int n;     pthread_t thread1;     pthread_t thread2;     void *a;     void *b;     int c;     n = (int)arg;     if (n <= 0) return 0;     if (n == 1) return 1;     pthread_create(&thread1, NULL, fib, n-1);    ...

  • can someone help me with changing this to c++ language #include <stdlib.h> #include <stdio.h> #include <pthread.h>...

    can someone help me with changing this to c++ language #include <stdlib.h> #include <stdio.h> #include <pthread.h> #include <string.h> #include <dirent.h> #include <sys/wait.h> #include <time.h> #include <sys/stat.h> #include <unistd.h> char *pathLog; char *pathRep;    struct stat attr; int fileNum, curNum; char *create_logPath(char *directory);    void *funcChecker(void *pathSub); void *funcprintTimeAndChanges(void *pathSub);    void main(int argc, char *argv[]) {    if(argc < 3)    { printf("%s must be executed with exactly two additional arguments (pathRep, pathSub)!\n", argv[0]); printf("Typed count is %d\n", argc); printf("Aborted...

  • #include <stdio.h> int main(int argc, char *argv[]) { int i; for (i = argc - 1;...

    #include <stdio.h> int main(int argc, char *argv[]) { int i; for (i = argc - 1; i > 0; i--) printf("%s ", argv[i]); printf("\n"); return 0; } can you explain this code in c and why use this function  

  • #include <stdlib.h> #include <stdio.h> #include "main.h" #define MAX_NUM_LENGTH 11 void usage(int argc, char** argv) { if(argc...

    #include <stdlib.h> #include <stdio.h> #include "main.h" #define MAX_NUM_LENGTH 11 void usage(int argc, char** argv) { if(argc < 4) { fprintf(stderr, "usage: %s <input file 1> <input file 2> <output file>\n", argv[0]); exit(EXIT_FAILURE); } } /* This function takes in the two input file names (stored in argv) and determines the number of integers in each file. If the two files both have N integers, return N, otherwise return -1. If one or both of the files do not exist, it...

  • include «stdio.h void displaymenu(void) printf(" printf" Enter Choicen") printf Set (a), Clear (c), Toggle (t)\n"): printf("...

    include «stdio.h void displaymenu(void) printf(" printf" Enter Choicen") printf Set (a), Clear (c), Toggle (t)\n"): printf(" void printbinaryfunsigned char x) int main (int argc, char argvl) r mask atoi(argv[1): unsigned char maskatoi(argv[11): ensigned ahao data - ateilargvl21): char operation if argc 3 printf(" printf" n" printf("usage: %s FristArg SecondArgin", argle)); return;

  • Please help i need a C++ version of this code and keep getting java versions. Please...

    Please help i need a C++ version of this code and keep getting java versions. Please C++ only Purpose: This lab will give you experience harnessing an existing backtracking algorithm for the eight queens problem, and seeing its results displayed on your console window (that is, the location of standard output). Lab A mostly complete version of the eight queens problem has been provided for you to download. This version has the class Queens nearly completed. You are to provide...

  • Fix the errors in C code #include <stdio.h> #include <stdlib.h> void insertAt(int *, int); void Delete(int...

    Fix the errors in C code #include <stdio.h> #include <stdlib.h> void insertAt(int *, int); void Delete(int *); void replaceAt(int *, int, int); int isEmpty(int *, int); int isFull(int *, int); void removeAt(int *, int); void printList(int *, int); int main() { int *a; int arraySize=0,l=0,loc=0; int choice; while(1) { printf("\n Main Menu"); printf("\n 1.Create list\n 2.Insert element at particular position\n 3.Delete list.\n4. Remove an element at given position \n 5.Replace an element at given position\n 6. Check the size of...

  • Complete the program that solves the Eight Queens problem in java only please (pages 318 through...

    Complete the program that solves the Eight Queens problem in java only please (pages 318 through 320). The program’s output should look similar to: |1|0|0|0|0|0|0|0| |0|0|0|0|0|0|1|0| |0|0|0|0|1|0|0|0| |0|0|0|0|0|0|0|1| |0|1|0|0|0|0|0|0| |0|0|0|1|0|0|0|0| |0|0|0|0|0|1|0|0| |0|0|1|0|0|0|0|0| PlaceQueens(in currColumn:integer) //places queens in columns numbered currColumn through 8 If (currColumn>8){ The problem is solved } Else { While(unconsidered squares exist in curr column and the problem is unsolved ){ Determine the next square in column currColumn that is not under attack by a queen in an...

  • #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> int main(void) { /* Type your code here....

    #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> int main(void) { /* Type your code here. */ int GetNumOfNonWSCharacters(const char usrStr[]) { int length; int i; int count = 0; char c; length=strlen(usrStr); for (i = 0; i < length; i++) { c=usrStr[i]; if ( c!=' ' ) { count++; } }    return count; } int GetNumOfWords(const char usrStr[]) { int counted = 0; // result // state: const char* it = usrStr; int inword = 0; do switch(*it)...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT