#!/usr/bin/perl -w # Check that all whitespace regions are connected. use strict; # Load input. my @lines = <>; chomp foreach @lines; # Find starting position. my ($x, $y); for($y = 0; $y < scalar @lines; $y++) { $x = index($lines[$y], " "); last if( $x >= 0 ); } unless( $x >= 0 ) { die "Input did not contain any space."; } # Floodfill. my @stack = ([$x, $y]); while( scalar @stack ) { ($x, $y) = @{pop @stack}; if( $y >= 0 && $y < scalar @lines && $x >= 0 && $x < length($lines[$y]) && substr($lines[$y], $x, 1) eq " " ) { substr($lines[$y], $x, 1) = "_"; push @stack, [$x, $y - 1], [$x - 1, $y], [$x, $y + 1], [$x + 1, $y]; } } # Check for disjoint spaces that were not touched by the floodfill. for($y = 0; $y < scalar @lines; $y++) { $x = index($lines[$y], " "); if( $x >= 0 ) { $x++; $y++; die "Found disjoint region at line $y column $x\n"; } } # Success. exit 0;