- 论坛徽章:
- 7
|
FOR print(path)
HERE:
- start = g.addVertex("fool")
- stop = g.addVertex("sage")
复制代码 if fool, sage not in wordslist:
1: addEdge for fool, sage!
2: WHY? NO edge => NO connectedTo => getConnections == []
3: HOW? ADD fool, sage TO wordslist
if fool, sage in wordslist
1: you RESET connectedTo = {}
2: WHY?
- newVertice = Vertex(key) # self.connectedTo = {}
- self.vertList[key] = newVertice
复制代码 3: SO getConnections == []
4: HOW? use:
- start = g.getVertex('fool')
- stop = g.getVertex('sage')
复制代码 1 ge bfs2 de lizi:
dict = [ 'hot', 'dot', 'dog', 'lot', 'log', 'hit', 'cog' ]
star = 'hit'
stop = 'cog'
output:- hit | hot | lot | log | cog
- hit | hot | dot | dog | cog
复制代码- #!/usr/bin/perl
- use 5.018;
- my %Graph;
- sub buildGraph {
- my $dic = shift;
- my $end = length( $dic->[0] ) - 1;
- for my $word (@$dic) {
- for ( 0 .. $end ) {
- my $pat = $word;
- substr( $pat, $_, 1 ) = '.';
- push @{ $Graph{$pat} }, $word;
- }
- }
- }
- sub getConnections {
- my $node = shift;
- map {
- my $p = $node;
- substr( $p, $_, 1 ) = '.';
- @{ $Graph{$p} || [] }
- } 0 .. length($node) - 1;
- }
- sub bfs2 {
- my ( $star, $stop ) = @_;
- my ( @todo, %has, %link ) = $star;
- while (@todo) {
- my %next;
- $has{$_} ||= 1 for @todo;
- for my $node (@todo) {
- for my $neibeer ( getConnections $node ) {
- next if $has{$neibeer};
- $next{$neibeer} ||= 1;
- push @{ $link{$neibeer} }, $node;
- }
- }
- @todo = keys %next;
- }
- sub {
- my ( $word, $a ) = @_;
- return join ' | ', $word, @$a if $word eq $star;
- map { __SUB__->( $_, [ $word, @$a ] ) } @{ $link{$word} };
- } ->( $stop, [] );
- }
- my $dict = [ 'hot', 'dot', 'dog', 'lot', 'log', 'hit', 'cog' ];
- my $star = 'hit';
- my $stop = 'cog';
- buildGraph $dict;
- my @path = bfs2 $star, $stop;
- say for @path;
复制代码 |
|