Ada - 遍历列表 - 我应该使用什么方法?

时间:2013-11-03 17:32:47

标签: recursion ada dijkstra breadth-first-search

我正在研究ADA项目。基本上我创建了一个列表和一个列表列表。

假设我有一个像A - >的列表B - > D - > E - > F,表示塔A连接到塔B,D,E和F.

现在我还需要一个列表来存储所有主塔。所以假设我有A - > B - > D - > E - > F,我有C-> X-> Y-> Q,而E-> P-> R,列表清单应该是这样的:

A-> C-> E(基本上是所有主节点的列表)。 如上所述,我有一个列表及其连接。现在我需要遍历这些列表以查明是否可以建立连接。例如:我有A - > B - > D - > E - > F和I具有C-> X-> Y-> Q和E-> P-> R。如果我被问到是A - > R可能的答案应该是真的。由于A - > E - > R. 我怀疑我应该采用什么方法? BFS?递归?什么是最好的?

1 个答案:

答案 0 :(得分:1)

嵌套for/of循环?像这样:

Function Exists( Target, Source : Node ) return boolean is
begin
    if Target = Source then
        return True;
    else
        for List of Source loop
            for Item of List loop
                if Item = Target then
                    return True;
                end if;
            end loop;
        end loop;
    end if;

    return false;
end Exists;

或者,如果您正在使用Vector for container,那么这个功能就是:

 function Contains
   (Container : Vector;
    Item      : Element_Type) return Boolean;

你会这样申请:

Package Inner_List is new Ada.Containers.Indefinite_Vectors(
                    Index_Type   => Positive,
                    Element_Type => Integer
                     );
Package Outer_List is new Ada.Containers.Indefinite_Vectors(
                    Index_Type   => Positive,
                    Element_Type => Inner_List.Vector,
                    "="          => Inner_List."="
                     );

Function Exists( Item : Integer; List : Outer_List.Vector ) return boolean is
begin
    for Items of List loop
        if Items.Contains(Item) then
            return true;
        end if;
    end loop;

    return false;
End Exists;