use strict;
use warnings;

my $file = 'nonogram_problems.txt';
open my $fd, '<', $file or die "$! opening $file";

while(my $row = <$fd> )
  {
  $row =~ /\S/ or next;
  my $column = <$fd>;
  my @rpats = makepatterns($row);
  my @cpats = makepatterns($column);
  my @rows = ( '.' x @cpats ) x @rpats;
  for( my $prev = ''; $prev ne "@rows"; )
    {
    $prev = "@rows";
    try(\@rows, \@rpats);
    my @cols = map { join '', map { s/.//; $& } @rows } 0..$
    try(\@cols, \@cpats);
    @rows = map { join '', map { s/.//; $& } @cols } 0..$
    }
  print "\n", "@rows" =~ /\./ ? "Failed\n" : map { tr/01/.
  }

sub try
  {
  my ($lines, $patterns) = @_;
  for my $i ( 0 .. $
    {
    while( $lines->[$i] =~ /\./g )
      {
      for my $try ( 0, 1 )
        {
        $lines->[$i] =~ s/.\G/$try/r =~ $patterns->[$i] or
          $lines->[$i] =~ s// 1 - $try /e;
        }
      }
    }
  }

sub makepatterns {                         
    map { qr/^$_$/                          
        } map {  '[0.]*'                    
               . join('[0.]+',              
                       map { "[1.]{$_}"     
                           } map { -64+ord  
                                 } split // 
                     )
               . '[0.]*'                    
              } split ' ', shift;           
}