in reply to Map grid to boundary conversion algorithm
Assuming there's no performance pressure, I think a straightforward search would be sufficient.
Here's an untested code outline:
use strict; # Build grid array my @grid; foreach ( <DATA> ) { s/^\s*\b// or next; push @grid, [ split ' ', $_ ], } # Assign arbitrary regions my @region; foreach my $x ( 0 .. $#grid ) { foreach my $y ( 0 .. $#{ $grid[0] } ) { $region[$x][$y] = "$x.$y"; } } # Merge neighboring regions foreach my $x ( 0 .. $#grid ) { foreach my $y ( 0 .. $#{ $grid[0] } ) { my @neighbors = ( [ $x-1, $y ], [$x, $y-1] ); foreach my $coord ( @neighbors ) { my ( $nx, $ny ) = @$coord; next if ( $nx < 0 or $ny < 0 ); if ( $grid[$x][$y] eq $grid[ $nx ][ $ny ] and $region[$x][$y] ne $region[ $nx ][ $ny ] ) { # Cell is the same color as its neighbor, join it merge_regions( $x, $y, $nx, $ny ) } } } } sub merge_regions { my ( $tx, $ty, $nx, $ny ) = @_; my $tr = $region[$tx][$ty]; my $nr = $region[$nx][$ny]; foreach my $x ( 0 .. $#grid ) { foreach my $y ( 0 .. $#{ $grid[0] } ) { if ( $region[$x][$y] eq $tr ) { $region[$x][$y] = $nr } } } } my $count = 0; my %regions; foreach my $x ( 0 .. $#grid ) { foreach my $y ( 0 .. $#{ $grid[0] } ) { my $num = ( $regions{ $region[$x][$y] } ||= ++ $count ); print $num . " "; } print "\n" } __DATA__ P P B R B P R B B B B R R R B B R R R B B G G B B
The output needs to be adjusted to your application; for now it just prints a grid of contiguous regions:
1 1 2 3 2 1 4 2 2 2 5 4 4 4 2 5 4 4 4 2 5 6 6 2 2
P.S. I've only seen "Moore Neighbourhood" used to refer to the immediate lateral and diagonal neighbors of a cell, but perhaps there's more than one meaning? Do you want to allow diagonal connections between neighbors, or only lateral ones?
Update: Looking at kvale's solution, I noticed that I implicitly assumed that the OP was looking for "contiguous regions" rather than "boundaries" -- it works out to the same thing, but influenced my choice of approach.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Map grid to boundary conversion algorithm
by pelagic (Priest) on Apr 16, 2004 at 19:05 UTC | |
by simonm (Vicar) on Apr 16, 2004 at 19:59 UTC |