首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >基于递归格式的点阵路径算法

基于递归格式的点阵路径算法
EN

Stack Overflow用户
提问于 2022-11-10 07:27:57
回答 1查看 66关注 0票数 1

我正在讨论一些递归方案,即变质和变形,并想尝试实现格点路径算法的解决方案,如下所述(摘自一系列采访问题):

代码语言:javascript
复制
Prompt:  Count the number of unique paths to travel from the top left
          order to the bottom right corner of a lattice of M x N squares.

          When moving through the lattice, one can only travel to the
          adjacent corner on the right or down.

 Input:   m {Integer} - rows of squares
 Input:   n {Integer} - column of squares
 Output:  {Integer}

 Example: input: (2, 3)

          (2 x 3 lattice of squares)
           __ __ __
          |__|__|__|
          |__|__|__|

          output: 10 (number of unique paths from top left corner to bottom right)**

使用正常的递归,您可以使用如下的方法来解决这个问题:

代码语言:javascript
复制
lattice_paths m n =
         if m == 0 and n == 0 then 1
         else if m < 0 or n < 0 then 0
         else (lattice_paths (m - 1) n) + lattice_paths m (n - 1)

我的Fixcataana的定义如下:

代码语言:javascript
复制
newtype Fix f = In (f (Fix f))

deriving instance (Eq (f (Fix f))) => Eq (Fix f)
deriving instance (Ord (f (Fix f))) => Ord (Fix f)
deriving instance (Show (f (Fix f))) => Show (Fix f)

out :: Fix f -> f (Fix f)
out (In f) = f

-- Catamorphism
type Algebra f a = f a -> a

cata :: (Functor f) => Algebra f a -> Fix f -> a
cata f = f . fmap (cata f) . out

-- Anamorphism
type Coalgebra f a = a -> f a

ana :: (Functor f) => Coalgebra f a -> a -> Fix f
ana f = In . fmap (ana f) . f

本文(https://stackoverflow.com/a/56012344)中提到的编写从Int -> Int开始的递归方案的方法是编写一个同胚,其中非变态类构建调用堆栈,而变形则构建所述调用堆栈的计算。我不知道怎么在这里建立调用堆栈。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-11-10 08:44:22

也许是这样的:

代码语言:javascript
复制
data CallStack a = Plus a a | Base Int deriving Functor

produceStack :: Coalgebra CallStack (Int, Int)
produceStack (m, n) =
    if m == 0 && n == 0 then Base 1
    else if m < 0 || n < 0 then Base 0
    else Plus (m-1, n) (m, n-1)

consumeStack :: Algebra CallStack Int
consumeStack (Base n) = n
consumeStack (Plus a b) = a + b

"Stack“是这个调用结构的一个有趣的名称。不是很像堆叠。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74385460

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档