#!/usr/bin/perl use strict; use warnings; my $n =($ARGV[0] || 8); # usage : perl queens.pl n # ex : perl queens.pl 20 ############# my $p=1; my (@s,@r); my $str; my $re='_(\d+)!'; for my $i (1..$n) { for my $j (1..$n) { $str.= join '!',"_$j",(map {join';',$j-$_<0?0:$j-$_,$j+$_ >$n?0:$j+$_} (1..($n-$i))),''; } $str.="\n"; push @s,$p+1,$p+2; push @r,$p; $re.=($i==$n)?'':(('(\d+);(\d+)!'x($n-$i)).".*?\n.*?_(?!(?:\\".(join '|\\',@r,@s).')!)(\d+)!'); $p+=2*($n-$i)+1; $_+=2 for @s; } my $l="a"; if ($str=~$re){print join",",map{$l++.eval"\$$_"}@r} else {print "no solution"} #print "\n\n",$str; #print "\n\n",$re; #### String (5x5 chess): _1!0;2!0;3!0;4!0;5!_2!1;3!0;4!0;5!0;0!_3!2;4!1;5!0;0!0;0!_4!3;5!2;0!1;0!0;0!_5!4;0!3;0!2;0!1;0! _1!0;2!0;3!0;4!_2!1;3!0;4!0;5!_3!2;4!1;5!0;0!_4!3;5!2;0!1;0!_5!4;0!3;0!2;0! _1!0;2!0;3!_2!1;3!0;4!_3!2;4!1;5!_4!3;5!2;0!_5!4;0!3;0! _1!0;2!_2!1;3!_3!2;4!_4!3;5!_5!4;0! _1!_2!_3!_4!_5! Regex: _(\d+)!(\d+);(\d+)!(\d+);(\d+)!(\d+);(\d+)!(\d+);(\d+)!.*? .*?_(?!(?:\1|\2|\3)!)(\d+)!(\d+);(\d+)!(\d+);(\d+)!(\d+);(\d+)!.*? .*?_(?!(?:\1|\10|\4|\5|\11|\12)!)(\d+)!(\d+);(\d+)!(\d+);(\d+)!.*? .*?_(?!(?:\1|\10|\17|\6|\7|\13|\14|\18|\19)!)(\d+)!(\d+);(\d+)!.*? .*?_(?!(?:\1|\10|\17|\22|\8|\9|\15|\16|\20|\21|\23|\24)!)(\d+)! Solution in : $1 $10 $17 $22 $25 _3!2;4!1;5! means : if in this line, the queen is in column "3" (_3!), then in next line queen will not be on column "2" or "4" (!2;4!) and in the line after queen will not be in col "1" or "5" (!1;5!) (diagonal)