Donnie Pryce
Donnie Pryce

Reputation: 1

Arrange queens on chess board

So I have to arrange 8 queens on a chess board so they can't kill each other. I've been working on this for a while and need some help. I started out by using a 2d array. I placed a 1, (a queen), randomly on the first row. I am trying to base the rest of the queens off of that position by going row by row and placing them in spots where the above and diagonal elements do not add to 1.

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

    #define dim 8


    int main(void)
    {
        int chess[dim] [dim] = {{0, 0, 0, 0, 0, 0, 0, 0},
                        {0, 0, 0, 0, 0, 0, 0, 0},
                        {0, 0, 0, 0, 0, 0, 0, 0},
                        {0, 0, 0, 0, 0, 0, 0, 0},
                        {0, 0, 0, 0, 0, 0, 0, 0},
                        {0, 0, 0, 0, 0, 0, 0, 0},
                        {0, 0, 0, 0, 0, 0, 0, 0},
                        {0, 0, 0, 0, 0, 0, 0, 0}}, i, j, *piece, vert_sum, diag_sum;

piece = &chess[0] [(rand() %8) + 1];
*piece = 1;

vert_sum = vert_sum + chess[i--] [j];
diag_sum = diag_sum + chess[i--] [j--];

for(i=1; i<8; i++)
{
    piece = &chess[i] [j=0];
    while(vert_sum == 1 || diag_sum == 1)
        {
            j++;

        }
    if(vert_sum != 1 && diag_sum != 1)
        {   

            *piece = 1;
        }
}

for(i=0; i<8; i++)
{
    for(j=0; j<8; j++)
    {
        printf("%d ", chess[i] [j]);
        if(j==7)
        {
            printf("\n");
        }
    }
}

}

pretty much everything from vert_sum = vert_sum +.... to if(vert_sum != 1 && diag_sum != 1){*piece = 1;} is random crap I've been trying out. Any help on what I cold do would be greatly appreciated.

Upvotes: 0

Views: 168

Answers (2)

Mike Bessonov
Mike Bessonov

Reputation: 686

Google "backtracking", this is the traditional way to solve the problem. The code presented has a long way to go towards it.

Upvotes: 0

Tin Rabzelj
Tin Rabzelj

Reputation: 132

This is a classic problem that can be solved using backtracking. You can look for pseudocode.

wiki

Upvotes: 1

Related Questions