#!/usr/bin/perl
use 5.016;
use warnings;
use utf8;
binmode STDOUT => ':encoding(utf8)';

sub f {
	my @lists = map{ [split //] } @_;

	my @queue = ([ [], [ (0) x @lists ] ]);
	while(@queue){
		my ($pattern, $pos) = @{ shift @queue };

		if (not grep{ @{$lists[$_]} > $pos->[$_] } (0 .. $#lists)){
			foreach(@lists){
				my @p = @{$_};
				foreach(@{$pattern}){
					@p or last;
					print($p[0] eq $_ ? shift(@p) : '□');
				}
				print "\n";
			}
			return;
		}

		my %memo;
		foreach my $n (0 .. $#lists){
			my $x = $lists[$n]->[$pos->[$n]];
			defined $x or next;
			if (not exists $memo{$x}){
				$memo{$x} = [ [ @{$pattern}, $x ], [ @{$pos} ] ];
				push @queue, $memo{$x};
			}
			$memo{$x}->[1]->[$n]++;
		}
	}
}

f(qw(１２３ １３４));
print "\n";
f(qw(１２１２ １３２２ １１２２));
print "\n";
