Perl 欧拉路径,有向图
晚上好。我真的是一个初学者,我正在一个欧拉路径的实现中工作。这意味着每个边(不是有向图的顶点)只能使用一次。 出于某种原因,它无法覆盖所有顶点,即使在纸上它应该覆盖。它似乎忽略了一半的顶点,或者只是不将它们添加到回路中 预期结果是:Perl 欧拉路径,有向图,perl,graph,Perl,Graph,晚上好。我真的是一个初学者,我正在一个欧拉路径的实现中工作。这意味着每个边(不是有向图的顶点)只能使用一次。 出于某种原因,它无法覆盖所有顶点,即使在纸上它应该覆盖。它似乎忽略了一半的顶点,或者只是不将它们添加到回路中 预期结果是: 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
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 $newlocation=@{$edges{$location}}[0];
splice @{$edges{$location}},0,1;
$location=$newlocation;
}
else
{
push @circuit, $location;
$location=pop @stack;
}
}
my @revcircuit= reverse @circuit;
print @revcircuit;
提前非常感谢您的见解 问题在于:
if (@{$edges{$location}}[0])
其中一个节点称为0,在Perl中为false。因此,一旦到达零节点,程序将继续运行,就像没有更多节点一样。
改用
这是一个工作版本,稍加编辑,例如删除了不必要的数组解引用:
#!/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.
问题在于:
if (@{$edges{$location}}[0])
其中一个节点称为0,在Perl中为false。因此,一旦到达零节点,程序将继续运行,就像没有更多节点一样。
改用
这是一个工作版本,稍加编辑,例如删除了不必要的数组解引用:
#!/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.
{…}定义哈希引用,而不是哈希。我无法运行此处显示的代码。非常抱歉。我不知道为什么,但我可以运行它。{…}定义了一个哈希引用,而不是哈希。我无法运行此处显示的代码。非常抱歉。我不知道为什么,但我可以运行它。哦,上帝,非常感谢!!效果非常好。我非常感激,真的。我怎样才能给你分数或什么?你保存了我的作业:@MarthaElenaIbarra你可以点击答案旁边的绿色勾号并投票哦,上帝,非常感谢!!效果非常好。我非常感激,真的。我怎样才能给你分数或什么?您保存了我的作业:@MarthaElenaIbarra您可以单击答案旁边的绿色勾号并向上投票