【发布时间】:2024-01-10 21:26:02
【问题描述】:
我正在尝试在 Prolog 中制作简单的图形着色算法,但我有点难以理解该语言。我知道我想做什么 - 我想去一个顶点,找到所有其他连接到它的顶点,检查我的顶点的颜色,并根据它用不同的颜色为其他顶点着色。我只是很难将其翻译成 Prolog。如果它是 C 方言或 Java,那对我来说简直是小菜一碟,但这让我很适应。
这是我目前所拥有的:
main:- graph_coloring.
%color_list([blue, red, green, yellow, white], colors).
%vertex_list([a, b, c, d], vertices).
%edge_list([(a,b),(b,c),(c,d)], edges).
%Our graph
color(blue).
color(red).
color(green).
color(black).
color(white).
%graph([a-b, b-c, b-d, c-d]).
vertex(a).
vertex(b).
vertex(c).
vertex(d).
%Subject to changing, so are asserted into listener at runtime.
init_dynamic_facts:-
assertz(vertex_color(a, none)),
assertz(vertex_color(b, none)),
assertz(vertex_color(c, none)),
assertz(vertex_color(d, none)),
assertz(location(a)).
edge(a,b).
edge(b,c).
edge(b,d).
edge(c,d).
is_connect(A,B):-
edge(A,B).
is_connect(A,B):-
edge(B,A).
connections(Vertex):-
edge(Vertex,X).
connections(Vertex):-
edge(X,Vertex).
move(Vertex):-
retract(location(_)),
asserta(location(Vertex)).
paint_vertex(Vertex, Color):-
retract(vertex_color(Vertex,_)),
asserta(vertex_color(Vertex, Color)).
find_vertex_color(Vertex):-
vertex_color(Vertex, X).
graph_coloring:-
location(Current_vertex),
vertex_color(Current_vertex, Curr_color),
( Curr_color =:= none ->
connections(Current_vertex, Others),
vertex_color(Others, Other_colors),
paint_vertex(Current_vertex,
如何完成这个算法?
(已编辑:graph_coloring 下有更多代码)
【问题讨论】:
-
你不想去一个未着色的顶点,然后选择一个没有被任何相邻顶点使用的颜色吗?
-
我从没有着色的顶点开始,但可以肯定的是,最好为第一个顶点分配颜色并按照您所说的去做。
-
您能具体说明您遇到的问题吗?
-
我正在尝试在 prolog 中进行图形着色算法,但它与我使用过的其他任何东西都如此不同,我什至不确定从哪里开始。例如,变量。它们在序言中的使用方式不同,我发现它们的要求甚至不同。例如,在 C# 中,我可以说 Variable_I_want = Method_that_returns_the_variable()。我不能在 prolog 中完全做到这一点,而且我还没有弄清楚如何以“prolog 方式”做到这一点。
-
也许你应该从更简单的开始,比如为你的所有顶点分配一种特定的颜色。
标签: algorithm prolog graph-theory graph-coloring