- 论坛徽章:
- 0
|
- #!perl
- use strict;
- use Data::Dumper;
- use constant MAX_DEPTH => 100;
- my @array = (
- ['a','b'],
- ['a','c'],
- ['b','e'],
- ['b','f'],
- ['c','e'],
- ['c','f'],
- ['b','c'],
- ['e','f'],
- );
- #make graph map
- my $map = {};
- for (@array) {
- push @{ $map->{$_->[0]} }, $_->[1];
- }
- #print Dumper($map);
- #start
- my @result = ();
- my $depth = 1;
- my @start_array = ();
- for (keys %$map) {
- push @start_array, { start => $_, end => $_, visited => { $_ => 1} };
- }
- while ( $depth <= MAX_DEPTH and @start_array > 0) {
- my @new_start_array = ();
- for my $to_expand (@start_array) {
- my $ra_can_expand = $map->{ $to_expand->{end} };
- for my $can_expand (@$ra_can_expand) {
- if (not $to_expand->{visited}->{$can_expand}) {
- my %tmp_visited = %{ $to_expand->{visited} };
- $tmp_visited{$can_expand} = 1;
- my $new = {
- start => $to_expand->{start},
- end => $can_expand,
- visited => \%tmp_visited,
- };
- push @new_start_array, $new;
- push @result, $new;
- }
- }
- }
-
-
- @start_array = @new_start_array;
- $depth++;
- }
- print "the all result is \n";
- for my $one (@result) {
- my $cost = ( keys %{ $one->{visited} } ) - 1;
- print $one->{start} . '-' . $one->{end} . " cost $cost\n";
- }
复制代码
[ 本帖最后由 xiaoshengcaicai 于 2007-2-8 22:46 编辑 ] |
|