68 lines
1.1 KiB
C
68 lines
1.1 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
|
|
int *board;
|
|
int target;
|
|
|
|
int ft_abs(int value)
|
|
{
|
|
if (value < 0)
|
|
return (value * -1);
|
|
return (value);
|
|
}
|
|
|
|
void print_board()
|
|
{
|
|
int i = 0;
|
|
while (i < target)
|
|
{
|
|
if (i == 0)
|
|
fprintf(stdout, "%i", board[i]);
|
|
else
|
|
fprintf(stdout, " %i", board[i]);
|
|
i++;
|
|
}
|
|
fprintf(stdout,"\n");
|
|
}
|
|
|
|
int is_safe(int row, int col)
|
|
{
|
|
int c = 0;
|
|
while (c < col)
|
|
{
|
|
if (board[c] == row)
|
|
return (0);
|
|
if (ft_abs(board[c] - row) == ft_abs(col -c))
|
|
return (0);
|
|
c++;
|
|
}
|
|
return (1);
|
|
}
|
|
|
|
void solve(int col)
|
|
{
|
|
if (col == target)
|
|
return (print_board());
|
|
|
|
int row = 0;
|
|
while (row < target)
|
|
{
|
|
if (is_safe(row, col))
|
|
{
|
|
board[col] = row;
|
|
solve(col + 1);
|
|
}
|
|
row++;
|
|
}
|
|
}
|
|
|
|
int main(int ac, char **av)
|
|
{
|
|
if (ac != 2)
|
|
return (1);
|
|
target = atoi(av[1]);
|
|
board = (int *)calloc(target, sizeof(int));
|
|
solve(0);
|
|
free(board);
|
|
return (0);
|
|
} |