93 lines
1.2 KiB
C
93 lines
1.2 KiB
C
#include <unistd.h>
|
|
#include <stdlib.h>
|
|
#include <stdio.h>
|
|
|
|
void ft_putchar(char c)
|
|
{
|
|
write(1, &c, 1);
|
|
}
|
|
|
|
void ft_putnbr(int n)
|
|
{
|
|
if (n >= 10)
|
|
ft_putnbr(n / 10);
|
|
ft_putchar((n % 10) + '0');
|
|
}
|
|
|
|
void print_solution(int *board, int n)
|
|
{
|
|
int i = 0;
|
|
while (i < n)
|
|
{
|
|
ft_putnbr(board[i]);
|
|
if (i < n - 1)
|
|
ft_putchar(' ');
|
|
i++;
|
|
}
|
|
ft_putchar('\n');
|
|
}
|
|
|
|
int ft_abs(int nbr)
|
|
{
|
|
if (nbr < 0)
|
|
return (nbr * -1);
|
|
else
|
|
return (nbr);
|
|
}
|
|
|
|
int is_safe(int *board, int n, int row, int col)
|
|
{
|
|
int i;
|
|
|
|
i = 0;
|
|
(void)n;
|
|
while (i < col)
|
|
{
|
|
if (board[i] == row)
|
|
return (0);
|
|
if (ft_abs(board[i] - row) == (col - i))
|
|
return (0);
|
|
i++;
|
|
}
|
|
return (1);
|
|
}
|
|
|
|
void solve(int *board, int n, int col)
|
|
{
|
|
if (col == n)
|
|
return(print_solution(board, n));
|
|
|
|
int row = 0;
|
|
while (row < n)
|
|
{
|
|
if (is_safe(board, n, row, col))
|
|
{
|
|
board[col] = row;
|
|
solve(board, n, col + 1);
|
|
}
|
|
row++;
|
|
}
|
|
}
|
|
|
|
int main(int argc, char **argv)
|
|
{
|
|
int *board;
|
|
int n;
|
|
|
|
if (argc != 2)
|
|
return (fprintf(stderr, "Usage: %s n\n", argv[0]), 1);
|
|
|
|
n = atoi(argv[1]);
|
|
if (n <= 0)
|
|
return (0);
|
|
|
|
board = (int *)malloc(sizeof(int) * n);
|
|
if (!board)
|
|
{
|
|
fprintf(stderr, "Memory allocation failed\n");
|
|
return (1);
|
|
}
|
|
solve(board, n, 0);
|
|
free(board);
|
|
return (0);
|
|
} |