Wednesday, February 3, 2016

[Algo] backtracking 回溯法

回溯法 是暴力搜寻法中的一种
 Tree :
Start from the root, DFS , when the result is not optimized, we track back to the root node and redo.

For any centain solution : when we got a solution, we stop.
For all solution : when we finished  Traversal every child of the root.

WHEN :
the principle of Backtracking is trying! So it can be used for most complex and big problems.

HOW :
  1.  define the space of solutions : give while a condition to stop
  2. define the rule of trying: Tree
  3. DFS the tree
Normal structure :
 Recursive :
   1: int a[n];
   2: try(int i)
   3: {
   4:     if(i>n)
   5:        输出结果;
   6:      else
   7:     {
   8:        for(j = 下界; j <= 上界; j=j+1)  // 枚举i所有可能的路径
   9:        {
  10:            if(fun(j))                 // 满足限界函数和约束条件
  11:              {
  12:                 a[i] = j;
  13:               ...                         // 其他操作
  14:                 try(i+1);
  15:               回溯前的清理工作(如a[i]置空值等);
  16:               }
  17:          }
  18:      }
  19: } 
 Non- Recursive : 
   1: int a[n],i;
   2: 初始化数组a[];
   3: i = 1;
   4: while (i>0(有路可走)   and  (未达到目标))  // 还未回溯到头
   5: {
   6:     if(i > n)                                              // 搜索到叶结点
   7:     {   
   8:           搜索到一个解,输出;
   9:     }
  10:     else                                                   // 处理第i个元素
  11:     { 
  12:           a[i]第一个可能的值;
  13:           while(a[i]在不满足约束条件且在搜索空间内)          // until find a valid value for a 
  14:           {
  15:               a[i]下一个可能的值;
  16:           }
  17:           if(a[i]在搜索空间内)
  18:          {
  19:               标识占用的资源;
  20:               i = i+1;                              // 扩展下一个结点
  21:          }
  22:          else 
  23:         {
  24:               清理所占的状态空间;            // 回溯
  25:               i = i –1; 
  26:          }
  27: }
[http://www.cnblogs.com/steven_oyj/archive/2010/05/22/1741376.html] 
Ex : 8 queens : https://en.wikipedia.org/wiki/Eight_queens_puzzle


https://leetcode.com/problems/n-queens/

No comments:

Post a Comment