Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- use strict;
- use warnings;
- use Data::Dumper;
- my @solution = ([], [], [], [], [], [], [], []); #board
- sub initial {
- for my $i (0 .. 7) {
- for (0 .. 7) {push @{$solution[$i]}, 0;} #create the board
- }
- }
- sub safe {
- my $row_safe = shift;
- my $col_safe = shift;
- if ($solution[$col_safe]->[$row_safe] == 0) {return 1;}
- else {return 0;}
- }
- sub mark {
- my $row_mark = shift;
- my $col_mark = shift; #get current col
- for my $c ($col_mark .. 7) { #from this col to the las col
- for my $r (0 .. 7) { #for each row
- if ($r == $row_mark && $c == $col_mark) {$solution[$c]->[$r] = $col_mark + 1;}
- #original answer will be marked as col+1
- elsif ($solution[$c]->[$r] == 0) {
- if ($r == $row_mark) {$solution[$c]->[$r] = 10 * ($col_mark + 1);}
- if ($r - $c == $row_mark - $col_mark) {$solution[$c]->[$r] = 10 * ($col_mark + 1);}
- if ($r + $c == $row_mark + $col_mark) {$solution[$c]->[$r] = 10 * ($col_mark + 1);}
- }#we check if the value there is 0 #we write 10* the original col+1, as attack area
- else {} # we do nothing if anything else
- }
- }
- }
- sub unmark {
- my $row_unmark = shift;
- my $col_unmark = shift; #get current col
- for my $c ($col_unmark .. 7) { #from this col to the las col
- for my $r (0 .. 7) { #for each row
- if ($r == $row_unmark && $c == $col_unmark) {$solution[$c]->[$r] = 0;} #original answer will be marked as col+1
- elsif ($solution[$c]->[$r] == 10 * ($col_unmark + 1)) { #we check if the value there is 0
- $solution[$c]->[$r] = 0;}
- #we write 10* the original col+1, as attack area
- else {} # we do nothing if anything else
- }
- }
- }
- sub solve {
- my $col_solve = shift; #for the col where we are
- if ($col_solve == 8) {
- process();
- return 1;
- }
- for my $row_solve (0 .. 7) { #for every row we are going to try
- if (safe($row_solve, $col_solve)) {
- mark($row_solve, $col_solve);
- solve($col_solve + 1);
- unmark($row_solve, $col_solve);
- }
- }
- }
- sub process {
- for my $rp (0 .. 7) {
- for my $cp (0 .. 7) {
- if ($solution[$rp]->[$cp] > 0 && $solution[$rp]->[$cp] < 10) {print "Q";} #create the board
- else {print "口";} #create the board
- }
- print "\n";
- }
- print "\n\n";
- }
- sub main {
- initial();
- solve(0);
- }
- main();
Add Comment
Please, Sign In to add comment