2016-04-03 84 views
1

晚上好。我真的是一个初学者,我正在实施一个欧拉路径。这意味着有向图的每个边(而不是顶点)只能被使用一次。 由于某些原因,即使在纸张上它应该也不能遍历所有的顶点。它似乎忽略了一半的顶点,或者根本就没有将它们添加到电路中。欧拉路径,有向图

预期的结果是:

6->7->8->9->6->3->0->2->1->3->4 

不过,我得到的结果是:

6 6 6 6 6 6 6 7 7 7 7 7 7 7 8 8 8 8 8 8 8 9 9 9 9 9 9 9 3 3 3 3 3 3 

我有什么作为代码如下:

my %edges={'6'=>['3','7'],'8'=>['9'],'1'=>['3'],'0'=>['2'],'3'=>['0','4'], '7' =>['8'],'9'=>['6'],'2'=>['1']}; 


    my $startvertex=6; #this i got from additional code 
    my $location=$startvertex; 
    my @stack = ($startvertex); 
    my @circuit =(); 

     while (@stack) 
     { 
      if (@{$edges{$location}}[0]) 
       { 
        push @stack, $location; 
        my [email protected]{$edges{$location}}[0]; 
        splice @{$edges{$location}},0,1; 
        $location=$newlocation; 

       } 
      else 
       { 
       push @circuit, $location; 
       $location=pop @stack; 
       } 

     } 

my @revcircuit= reverse @circuit; 
print @revcircuit; 

非常感谢你提前了解您的洞察力。

+0

'{...}'定义一个哈希引用,而不是散列。我不能像这里介绍的那样运行你的代码。 – choroba

+0

非常抱歉。我不知道为什么,但我可以运行它。 –

回答

5

问题就在这里:你

节点
if (@{$edges{$location}}[0]) 

一个叫0这是假的在Perl。因此,一旦达到零节点,程序继续,就好像没有更多的节点。 改为使用defined

这里的一个工作版本,编辑略微(例如去除不需要的阵列解引用):

#!/usr/bin/perl 
use warnings; 
use strict; 

my %edges = (6 => [3, 7], 
       8 => [9], 
       1 => [3], 
       0 => [2], 
       3 => [0, 4], 
       7 => [8], 
       9 => [6], 
       2 => [1]); 

my $startvertex = 6; 

my $location = $startvertex; 
my @stack = ($startvertex); 
my @circuit; 

while (@stack) { 
    if (defined $edges{$location}[0]) { 
     push @stack, $location; 
     $location = shift @{ $edges{$location} }; 
    } else { 
     push @circuit, $location; 
     $location = pop @stack; 
    } 
} 
my @revcircuit = reverse @circuit; 
print "@revcircuit\n"; 

还要注意的是,它使用圆括号定义%edges散列。大括号引入哈希引用,与他们我得到

Reference found where even-sized list expected at ./1.pl line 5. 
+0

天啊,非常感谢!作品非常好。我非常感激,真的。 –

+0

我该如何给你点或什么?你保存了我的作业:) –

+0

@MarthaElenaIbarra你可以点击答案旁边的绿色勾号(也可以将其提升) – Zaid