列为序言中的图表 [英] List as graph in prolog

查看:71
本文介绍了列为序言中的图表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试生成从矩阵中的一个元素到另一元素的所有可能的路线",主要条件是说,只有当元素在该矩阵中共享至少一个角时,矩阵中的元素才能与其他元素连接

I'm trying to generate all possible 'ways' from one element in matrix to another, Main conditional says that Element in matrix can be connected with other only if elements share at least one corner so in that matrix

[[1,2,3]
 [5,4,6]
 [8,9,7]]

1只能与2,4,5连接,而4与所有元素都连接.是否可以在不使用吸引的情况下将该列表表示为图形?也许我可以找到更简单的方法

1 can be only conected with 2,4,5 but 4 is conected with all elements. Is it possible to represent that list as graph without using attract? Or maybe I can find out any easier way to do it

感谢所有答案. 好吧,我提出:-) 现在有了谓词,我生成了所有边",但是我无法在任何地方使用它们,我无法弄清楚如何使用这种模式([row:R1,column:C1,value:V1], [row:R2,column:C2,value:V2])将每个单元的累加信息添加到累加器(列表)中.

Thanks for all answers. Ok i set forth :-) Now with predicates I generated all 'edges' but i cannot use them anywhere, I could not figure out, how to add to accumulator(list) infomrations of each cell with such pattern ([row:R1,column:C1,value:V1], [row:R2,column:C2,value:V2]).

推荐答案

使用Prolog回溯可以轻松完成有限集的枚举:

Enumeration of a finite set can be done easily using Prolog backtracking:

adjacent_pos((R,C), (Ra,Ca)) :-
     (R > 1, Ra is R-1 ; Ra is R ; Ra is R+1),
     (C > 1, Ca is C-1 ; Ca is C ; Ca is C+1),
     once(Ra \= R ; Ca \= C).

使用配对的nth1/3,我们可以访问一个单元格:

Using paired nth1/3 we can access a cell:

cell(Mat, (R,C), Cell) :-
     nth1(R, Mat, Row),
     nth1(C, Row, Cell).

因此,在不同元素的矩阵NxM中:

So, in a matrix NxM of distinct elements:

adjacent(Mat, Elem, Adj) :-
     cell(Mat, Pe, Elem),
     adjacent_pos(Pe, Pa),
     cell(Mat, Pa, Adj).

简单测试:

test :-
   M = [[1,2,3],
        [5,4,6],
        [8,9,7]],
   findall(A, adjacent(M,1,A), L1), writeln(L1),
   findall(A, adjacent(M,4,A), L4), writeln(L4).

产量:

?- test.
[2,5,4]
[1,2,3,5,6,8,9,7]
true.

请注意,可以避免测试R > 1C > 1,要求在带外"测试中失败nth1/3.上限也是如此,实际上已被省略,其附加好处是我们不仅限于预定义的矩阵大小.

Note that the test R > 1 and C > 1 could be avoided, demanding to nth1/3 failure the 'out of band' test. The same is true for the upper limit, omitted indeed, with the added benefit that we are not limited to a predefined matrix size.

这篇关于列为序言中的图表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆