Eight Queens

For this program, I have to determine if the given configuration has exactly one queen in each row and one in each column. If it does, the program outputs "Yes" and if not, it outputs "No". I have everything correct except for i need to fix the nested for loop towards the bottom. Just can't figure out how to make it execute correctly. Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
  #include <iostream>
using namespace std;

int main( )
{
    // declare integers
    int board [8];
    bool flag = true;
    
    // initial output
    cout << "Enter the rows containing queens, in order by column: ";
    
    // for loop for input
    for (int i=0; i<8; i++)
    {
        cin >> board [i];
    }
    cout << endl;
    
    // for loop for rows
    for (int r=0; r<8; r++)
    {
        // for loop for columns
        for (int c=0; c<8; c++)
        {
            if (i == board[i])
            {
                flag = true;
                cout << "Yes";
            }
            else
            {
                cout << "No";
            }
        }
        cout << endl;
    }
}
Hello RP366336,

On line 7 you define a 1D array yet line 21 on looks like you want to deal with a 2D array.

The outer loop for rows has no real use except to loop through your 1D array eight times.

The "cout statements on lines 29 and 33 will print each time through the 1D array and then do it seven more times.

Line 11 asks for rows, but line 14 only deals with one row because you only have a 1D array.

Unless you are trying to use the 1D array eight different times.

Hope that helps,

Andy
"Enter the rows containing queens, in order by column: "

Does that mean that one element in 'board' is one column on the board and the value in that element tells on which row of that column the Queen is?

If so, there is exactly one Queen on each column. What remains to be checked is whether two or more Queens are on the same row.

For example:
1
2
3
4
5
6
7
bool unique = true;
for ( int pivot=0; pivot < 7; ++pivot ) {
  IF any of board[pivot+1 .. 7] has same value as board[pivot]
  THEN unique = false, break
}

if ( unique ) ...
I think you're trying to use a 1D array to simulate a 2D config of queens, which is fine, but wouldn't you want the indices of the array to be the rows?

Input: 1 2 3 6 0 7 5 4
(index 0 1 2 3 4 5 6 7)

Translation -- Queens appear at
Row0, Column1
Row1, Column2
Row2, Column3
Row3, Column6
Row4, Column0
Row5, Column7
Row6, Column5
Row7, Column4

From here you can realize you don't need a nested loop at this stage and need only see if all the input is unique from 0 to 7. I'd also like to point out that you're solving an 8 Rooks problem, not an 8 Queens problem.
Topic archived. No new replies allowed.