簡體   English   中英

檢查是否連接了兩個節點

[英]Check if two nodes are connected

g為無向圖,為簡單起見,我們將其表示為成對的Integers對列表。 例如

g = [(1,1),(2,2),(3,3),(4,4),(1,2),(2,3),(1,3)]

假設我已經定義了一個函數adj node ,該節點將相鄰節點的有序列表提供給g node 例如

> adj 1
[2,3]
> adj 4
[]

我想檢查兩個節點是否以遞歸方式看向相鄰節點,將其歸納為任意數量的檢查

connected start end
| start == end = True
| elem end (adj start) = True
| elem end (extract (map adj (adj start))) = True
| elem end (extract (map adj (extract (map adj (adj start))))) = True
  -- to make this function work on a graph or arbitrary size, I should put here
  -- an endless number of lines like the ones above
| otherwise = False
where
    extract (x:xs) = x ++ extract xs
    extract _ = []

要進行遞歸檢查,您必須執行一個遞歸調用。 在這里,它只是關於應用連接到adj start所有成員,並查看是否有任何結果是正確的:

connected :: Int -> Int -> Bool
connected start end | elem end adjs = True
                    | otherwise     = any (flip connected end) $ adjs
  where  adjs = adj start

您還必須檢查周期。 作為第一種方法,可以通過保留已遇到的節點列表來完成。 如果您關心性能和大圖,則可能需要使用除基本列表以外的其他方法:

connected :: Int -> Int -> Bool
connected start end = go start end [start]
  where
    go start end seen | elem end adjs = True
                      | otherwise     = any (\x -> go x end (x:seen))
                                        . filter (not . (flip elem seen))
                                        $ adjs
      where adjs = adj start

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM