1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!perl

use strict;
use warnings;

my @landscape;
my $debug = 0;

sub flood {
	my ($row, $start, $end) = @_;
	my $current = $end - $start;
	(my $line = $landscape[$row]) =~ s/(.{0,$start})(.{0,$current})/$1<$2>/;

print "[$line]\n" if $debug;

	my $flood = 1;
	if ($line =~ /[ x]>/ and is_air($end - 1, $row) and $flood = $line =~ m~>[ _xy]*[\\/]~) {
		$end = $+[0] - 2;
	}
	elsif ($line =~ /[ _]*>/) {
		$end = $-[0] - 1;
	}

	if ($line =~ /<[ x]/ and is_air($start, $row) and $flood &&= $line =~ m~[\\/][ _xy]*<~) {
		$start = $-[0];
	}
	elsif ($line =~ /<[ _]*/) {
		$start = $+[0] - 1;
	}

print '+' . '-' x $start . '[' . substr($landscape[$row], $start, $end - $start) . "]\n" if $debug;

	if ($flood && $start < $end) {
		my $t;
		substr($landscape[$row], $start, $end - $start) =~
			s!([\\/][ _xy]*)([\\/][ _]*)!($t = $1) =~tr/ _/xy/, $t . $2!eg;

print ">[${landscape[$row]}]\n" if $debug;

		$row--;  
		flood($row, $start, $end) if $row;
	}
}

sub is_air {
	my ($air, $x, $y) = (1, @_);
		
	foreach my $row (0 .. $y - 1) {
		my $line = ' ' . $landscape[$row];

		next if $x >= length($landscape[$row]);
		$air ^= substr($line, $x, 3) =~ /^(.[_y]|.\/([^_]|$)|[^_]\\)/;
	}
	return $air % 2;
}

while (<>) {
	chomp;
	push @landscape, $_;
}

foreach my $row (reverse 0 .. $#landscape) {
	while ($landscape[$row] =~ m~\\/|[\\/]([_y]+)[\\/]~g) {
		if (is_air($-[0] + 1, $row)) {
			substr($landscape[$row], $-[1], length($1)) =~ tr/_y/x/ if defined $1;

print '=' . '-' x length($`) . "[$&]\n~[${landscape[$row]}]\n" if $debug;

			flood($row - 1, $-[0], $+[0]) if $row > 0;
		}
	}
}

for (@landscape) {
	tr/y/x/;
	print "$_\n";
}