94 lines
2.0 KiB
C
94 lines
2.0 KiB
C
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* ft_ten_queens_puzzle.c :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: tosuman </var/spool/mail/tosuman> +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2023/03/30 17:05:04 by tosuman #+# #+# */
|
|
/* Updated: 2023/03/30 17:05:06 by tosuman ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include <unistd.h>
|
|
#include <stdio.h>
|
|
#define SIZE 10
|
|
|
|
void ft_putchar(char c)
|
|
{
|
|
write(1, &c, 1);
|
|
}
|
|
|
|
// print the current board and return sols+1
|
|
int new_sol(int cols[SIZE], int sols)
|
|
{
|
|
int i;
|
|
|
|
i = -1;
|
|
while (++i < SIZE)
|
|
ft_putchar(cols[i] + '0');
|
|
ft_putchar('\n');
|
|
return (sols + 1);
|
|
}
|
|
|
|
int is_valid_board(int cols[SIZE], int col)
|
|
{
|
|
int i;
|
|
|
|
i = col;
|
|
while (--i >= 0)
|
|
if (cols[i] == cols[col])
|
|
return (0);
|
|
i = 0;
|
|
while (++i <= cols[col])
|
|
if (cols[col - i] == cols[col] - i && i <= col)
|
|
return (0);
|
|
i = 0;
|
|
while (++i < SIZE - cols[col] && i <= col)
|
|
{
|
|
if (cols[col - i] == cols[col] + i)
|
|
return (0);
|
|
}
|
|
return (1);
|
|
}
|
|
|
|
int backtrack(int cols[SIZE], int col, int sols)
|
|
{
|
|
int i;
|
|
|
|
if (col >= SIZE)
|
|
{
|
|
return (new_sol(cols, sols));
|
|
}
|
|
i = -1;
|
|
while (++i < SIZE)
|
|
{
|
|
cols[col] = i;
|
|
if (is_valid_board(cols, col))
|
|
sols += backtrack(cols, col + 1, 0);
|
|
cols[col] = -1;
|
|
}
|
|
return (sols);
|
|
}
|
|
|
|
int ft_ten_queens_puzzle(void)
|
|
{
|
|
int cols[SIZE];
|
|
int i;
|
|
|
|
i = -1;
|
|
while (++i < SIZE)
|
|
cols[i] = -1;
|
|
return (backtrack(cols, 0, 0));
|
|
}
|
|
|
|
/* ////
|
|
#include <stdio.h>
|
|
|
|
int main(void)
|
|
{
|
|
printf("%d\n", ft_ten_queens_puzzle());
|
|
return (0);
|
|
}
|
|
*/ ////
|