2016-04-03 42 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