回溯算法和贪心算法_回溯算法介绍

回溯算法和贪心算法

回溯算法 (Backtracking Algorithms)

Backtracking is a general algorithm for finding all (or some) solutions to some computational problems, notably constraint satisfaction problems. It incrementally builds candidates to the solutions, and abandons each partial candidate (“backtracks”) as soon as it determines that the candidate cannot possibly be completed to a valid solution.

回溯是一种通用算法,用于查找某些计算问题(尤其是约束满足问题)的所有(或某些)解决方案。 它逐步为解决方案构建候选对象,并在确定候选对象不可能完成有效的解决方案后立即放弃每个部分候选对象(“回溯”)

示例问题(骑士的旅行问题) (Example Problem (The Knight’s tour problem))

The knight is placed on the first block of an empty board and, moving according to the rules of chess, must visit each square exactly once.

骑士被放置在一个空棋盘的第一块上,并且根据国际象棋的规则移动,必须对每个广场精确地访问一次。

骑士走过的路覆盖了所有牢房 (Path followed by Knight to cover all the cells)

Following is chessboard with 8 x 8 cells. Numbers in cells indicate move number of Knight.

以下是带有8 x 8格的棋盘。 单元格中的数字表示骑士的移动次数。

骑士之旅的朴素算法 (Naive Algorithm for Knight’s tour)

The Naive Algorithm is to generate all tours one by one and check if the generated tour satisfies the constraints.

朴素算法是一一生成所有巡视,并检查生成的巡视是否满足约束条件。

while there are untried tours
{ 
   generate the next tour 
   if this tour covers all squares 
   { 
      print this path;
   }
}

骑士之旅的回溯算法 (Backtracking Algorithm for Knight’s tour)

Following is the Backtracking algorithm for Knight’s tour problem.

以下是骑士巡回问题的回溯算法。

If all squares are visited 
    print the solution
Else
   a) Add one of the next moves to solution vector and recursively 
   check if this move leads to a solution. (A Knight can make maximum 
   eight moves. We choose one of the 8 moves in this step).
   b) If the move chosen in the above step doesn't lead to a solution
   then remove this move from the solution vector and try other 
   alternative moves.
   c) If none of the alternatives work then return false (Returning false 
   will remove the previously added item in recursion and if false is 
   returned by the initial call of recursion then "no solution exists" )

翻译自: https://www.freecodecamp.org/news/backtracking-algorithms-explained/

回溯算法和贪心算法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值