use integer;
while(<>){
for $i(1..$n){
$_=<>;
@_=/\d/g;
$j=0;
$b[++$j][$i]=$_ for @_;
}
$_=<>;
@a=(1, 0, -1, 0);
$d=0;
$x = $y = 0;
$ans=0;
while (/\w/g){
$d += $inc = $& cmp M;
$inc and next;
# print "up/left:$b[$x][$y]|up/rigth:$b[$x+1][$y]|down/left:$b[$x][$y+1]|down/right:$b[$x+1][$y+1]\n";
print "$b[$x][$y]|$b[$x+1][$y]|$b[$x][$y+1]|$b[$x+1][$y+1]\n";
if ($a[ $d % 4 ] == 1){
$ans += $b[$x+1][$y+1] + $b[$x+1][$y];
$b[$x+1][$y+1] /= 2;
$b[$x+1][$y] /= 2;
}
if ($a[ $d % 4 ] == -1){
$ans += $b[$x][$y+1] + $b[$x][$y];
$b[$x][$y+1] /= 2;
$b[$x][$y] /= 2;
}
if ($a[ ($d-1) % 4 ] == -1){
$ans += $b[$x+1][$y] + $b[$x][$y];
$b[$x+1][$y] /= 2;
$b[$x][$y] /= 2;
}
if ($a[ ($d-1) % 4 ] == 1){
$ans += $b[$x+1][$y+1] + $b[$x][$y+1];
$b[$x+1][$y+1] /= 2;
$b[$x][$y+1] /= 2;
}
$x += $a[ $d % 4 ];
$y += $a[ ($d-1) % 4 ];
}
}
dXNlIGludGVnZXI7CndoaWxlKDw+KXsKCQoJKCRuLCRtKT1zcGxpdC8gLzsKCWZvciAkaSgxLi4kbil7CgkJJF89PD47CgkJY2hvbXA7CgkJQF89L1xkL2c7CgkJJGo9MDsKCQkkYlsrKyRqXVskaV09JF8gZm9yIEBfOwoJCX0KCQkKCSRfPTw+OwoJCglAYT0oMSwgMCwgLTEsIDApOwoJJGQ9MDsKCSR4ID0gJHkgPSAwOwoJJGFucz0wOwoJCgl3aGlsZSAoL1x3L2cpewoJCQoJCSRkICs9ICRpbmMgPSAkJiBjbXAgTTsKCQkkaW5jIGFuZCBuZXh0OwojCQlwcmludCAidXAvbGVmdDokYlskeF1bJHldfHVwL3JpZ3RoOiRiWyR4K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