8 queens

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • AZRebelCowgirl73
    New Member
    • Nov 2006
    • 47

    #1

    8 queens

    I am trying to develop an 8 queens program, and currently it is working however it is printing 87222211 which is obviously wrong, I am trying to print the row of the queen in order from column0-column7 of an array. I am new to C++ and was wondering if anyone could see my mistake? Thanks for taking a look. Here is my code.
    Code:
    int a[8];
     
    void display ();
     
    int TestLegal (int currentColumn, int currentRow)
    {
    	for (int column = 0; column < currentColumn; ++column)	//check row conflict
    		if (a[column] == a[currentColumn])	
    		return (0);	// return FALSE if both queens are on the same row
    	
    	for (int column = 0; column < currentColumn; ++column)	//check diagonal conflict
    		if (abs(a[column] - column) == (abs(a[currentColumn] - currentColumn)))
    		return (0);   // return FALSE if both queens are on the same diagonal.
    	return currentRow;
    }
     
    int placeQueen (int column) {
      if (column == 8)	//Check if all columns have a legal value
      {
        display();
        return (-1);
      }
     
      for (int row = 1; row <= 8; ++row)  // Try all of the legal values for the column
      {
        if (TestLegal (column, row))
        {
          a[column] = row;
          if (placeQueen (column + 1) < 0)
            return -1;
        }
      }
      return (0);
    }
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    I have removed some of your (non-relevant) code because we forbid posting complete answers to homework questions. I am assuming this is a homework question on the grounds I had to do the same question for homework when I was learning prolog (18 years ago).

    To answer you queries

    Code:
    		if (abs(a[column] - column) == (abs(a[currentColumn] - currentColumn)))
    		return (0);   // return FALSE if both queens are on the same diagonal.
    I do not believe this is correct logic for calculating if 2 queens are on the same diagonal. I suggest you get a chess board and run a few examples using pen and paper.

    Code:
        if (TestLegal (column, row))
        {
          a[column] = row;
          if (placeQueen (column + 1) < 0)
            return -1;
        }
    The call to TestLegal uses a[column] in it's calculations but you do not set a[column] until after the call returns.


    a is a very poor name for a variable.

    Comment

    Working...