piscine/c05/ex08/ft_ten_queens_puzzle.c
Willem Haffmans 607ce08c18 all
2024-09-10 00:18:01 +02:00

99 lines
1.9 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_ten_queens_puzzle.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: whaffman <whaffman@student.codam.nl> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/06/13 13:11:27 by whaffman #+# #+# */
/* Updated: 2024/06/15 11:24:16 by whaffman ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
#include <stdio.h>
#define SIZE 10
void ft_put_board(int board[SIZE])
{
int i;
char c;
i = 0;
while (i < SIZE)
{
c = board[i] + '0';
write(1, &c, 1);
i++;
}
write(1, "\n", 1);
}
int ft_test_queens(int board[SIZE], int x, int y)
{
int i;
i = 0;
if (x == 0)
return (1);
while (i <= x)
{
if (board[i] == y || i + board[i] == x + y || i - board[i] == x - y)
return (0);
i++;
}
return (1);
}
void ft_add_queen(int board[SIZE], int *res, int x)
{
int y;
if (x == SIZE)
{
*res += 1;
ft_put_board(&board[0]);
}
else
{
y = 0;
while (y < SIZE)
{
ft_put_board(&board[0]);
if (ft_test_queens(board, x, y))
{
board[x] = y;
ft_add_queen(board, res, x + 1);
board[x] = -3;
}
y++;
}
}
}
int ft_ten_queens_puzzle(void)
{
int res;
int board[SIZE];
int i;
i = 0;
res = 0;
while (i < SIZE)
{
board[i] = -3;
i++;
}
ft_add_queen(board, &res, 0);
return (res);
}
#ifdef DEBUG
int main(void)
{
printf("result = %d", ft_ten_queens_puzzle());
}
#endif