Prolog grade counter and eulerpath
this week I got this homework to do: count the grade of nodes in a undirected graph and test if there is a euler path in it. the function should work like following:
gradliste([[a,b],[b,c],[b,g],[c,d],[d,e],[e,f],[f,g],[g,h],[c,f]],X).
X开发者_高级运维 = [[a, 1], [b, 3], [c, 3], [g, 3], [d, 2], [e, 2], [f, 3], [h, 1]]
testEulerweg([[a,b],[b,c],[c,d],[d,e],[a,e],[b,d],[b,e],[a,d]]).
true.
my first idea of the functiongradliste
is to 'merge' the graph and generate a list like this:
[a,b,b,c,b,g,c,d,d,e,e,f,f,g,g,h,c,f]
then I count numbers of every node. unfortunately I stucked at the merge
.
and for the second function testEulerweg
I think I should firstly write a function allconnected
working like following:
allconnected([[a,b],[b,c],[c,d]]).
true.
allconnected([[a,b],[b,c],[e,f]]).
False.
then I can check if there are none or 2 nodes with odd grade number using the gradliste
function.
Can anyone help me on my idea? I'm also open for new ideas:)
thanks in advance
bearzk
The merge
function is simple. I'll rename it flatten
:
flatten([[X,Y] | Edges], [X,Y|Rest]) :-
flatten(Edges, Rest).
And I'll let you write the base case.
As for finding the Eulerian path, check out the algorithms at Wikipedia. The second one can be easily implemented in terms of select/3
, as long as you don't flatten
the list first :)
精彩评论