Showing posts with label Program. Show all posts
Showing posts with label Program. Show all posts

Tuesday, April 21, 2009

Python Study -- Get Environment


os.getenv(key, default=value)

Get the "key" environment variable, if it is not defined, use the default value as the result.

#!/usr/bin/env python
import osimport sys
VT_ROOT = os.getenv("VDE_TOOL_DIR", default = "/opt/vde/services/instances/vt2124")VT_CMD = VT_ROOT + "/bin/vde_tool"CT_CMD = VT_CMD + " ct "
print CT_CMDos.system

Thursday, December 4, 2008

Dealing with Command Line Options in Python

I just wrote a bit of Python to generate some reports from the contents of a database. The one program that was more than just "display the data" was the one to print the transaction log. It included some sub-totals for various fields and paginated output.

The one task remaining was to give it some options. That is, to pass it some criteria that would modify the report. Specifically, I wanted a start and end date and the ability to change the sort order from the default which was transaction date.

Before just jumping into the brute force way of dealing with the command line I decided to see if there was anything interesting in the Python libraries that might turn this into something a bit more pleasant. Well, I found good news in the form of the optparse module. From O'Reilly's Python in a Nutshell, I found the following description:

The optparse module offers rich, powerful ways to parse the command-line options that the user passed upon starting your programs.

Sounds good. My next check was on python.org with equally positive information. So, I decided to give it a try. Here is the short story (followed by a bit of code).

  • First you instantiate the class OptionParser.
  • For each option you want to use, you use the add_option method where you can specify the options (both short and long ones are supported) and tell optparse what to do.
  • Once you are all set up, you use the parse_args method to do all the dirtywork. You then can just check for the existence of the options by checking for an attribute.
opts = OptionParser()
opts.add_option("--start", "-s", help="in format yyyy-mm-dd")
opts.add_option("--end", "-e", help="in format yyyy-mm-dd")
opts.add_option("--order", "-o", type="choice", choices=["tdate", "cname_id",
"account_id", "project_id", "id"], help="tdate|cname_id|account_id|project_id|id")
options, arguments = opts.parse_args()

if options.start:
...
if options.order:
...

That should be enough code. Each of the opts.add_option( lines adds an option to the list. For example, the first one says that it matches either --start or -s. The implied action is to store the argument associated with it. The help argument is used to specify a help message that is printed out either in case of an error calling the command or if the command is invoked with the -h option.

The third opts.add_option( line is a bit different. It defines the type of option as a choice and then includes a list of valid values. Entering anything other than one of these values results in an error message including the usage display.

The call to opts.parse_args() does the dirtywork for you. For example, if I had invoked the program with -s 2008-11-11 then options.start would be set to 2008-11-11.

All in all, I found optparse easy to understand and enjoyed separating all the error checking from using the arguments. There are lots more things it can do for you but this should get you started. It is now in my list of "Python tricks". __________________________

Phil Hughes

Thursday, October 2, 2008

Bash Parameter Expansion

If you use bash you already know what Parameter Expansion is, although you may have used it without knowing its name. Anytime you use a dollar sign followed by a variable name you're doing what bash calls Parameter expansion, eg echo $a or a=$b. But parameter expansion has numerous other forms which allow you to expand a parameter and modify the value or substitute other values in the expansion process.

Parameter expansion comes in many forms in bash, the simplest is just a dollar sign followed by a name, eg $a. This form merely substitutes the value of the variable in place of the parameter expansion expression. The variable name can also optionally be surround by braces, eg ${a}. If the variable name is immediately followed by characters that could be part of a variable name then the braces are needed to delimit the variable name, for example if you remove the braces from echo ${a}bc bash will try to expand the variable "abc" rather than "a".

One useful form of parameter expansion is to use a default value for a variable if it is not set. This is done with the syntax: ${VAR:-DFLT}. You might use this to allow your code to be modified via variables from the environment. Consider the following from a script, call it test.sh:

  TEST_MODE=${TEST_MODE:-0}
...
if [[ $TEST_MODE -eq 0 ]]; then
echo "Running in live mode"
else
echo "Running in test mode"
fi
Normally the script runs in "live" mode but if you run it via:
  $ env TEST_MODE=1 sh test.sh
it runs in test mode.

You might also use the default value expansion with command line arguments or values from a config file, for example:

  # set cmd_param_x to 1 if seen on the command line
...
if [[ ${cmd_param_x:-0} -eq 0 ]]; then
echo "-x not specified"
else
echo "-x specified"
fi

Another useful form of parameter expansion is to expand a variable and do string substitution on the value using the form ${VAR/search/replace}. For example:

  VAR=aabbcc
echo ${VAR/b/-dd-}
outputs "aa-dd-bcc". Note that only the first instance of the search string is replaced, if you want to replace all instances use a double slash:
  VAR=aabbcc
echo ${VAR//b/-dd-}
which now outputs "aa-dd--dd-cc".

There are also expansions for removing prefixes and suffixes. The form ${VAR#pattern} removes any prefix from the expanded value that matches the pattern. The removed prefix is the shortest matching prefix, if you use double pound-signs/hash-marks the longest matching prefix is removed. Similarily, the form ${VAR%pattern} removes a matching suffix (single percent for the shortest suffix, double for the longest). For example:

  file=data.txt
echo ${file%.*}
echo ${file#*.}
outputs the file base and extension respectively ("data" and "txt").

Note: if you have trouble remembering which is which of these two syntaxes, the "#" is to the left of the "%" key on your keyboard, just as prefixes come before suffixes. Also note that these are glob patterns not regular expressions.

Another expansion that exists is to extract substrings from the expanded value using the form ${VAR:offset:length}. This works in the expected form: offsets start at zero, if you don't specify a length it goes to the end of the string. For example:

  str=abcdefgh
echo ${str:0:1}
echo ${str:1}
outputs "a" and "bcdefgh".

This form also accepts negative offsets which count backwards from the end of the string. So this:

  str=abcdefgh
echo ${str:-3:2}
produces "abcdefgh"... oops, what happened there? What happened was that bash misinterpretted what we wanted because the expansion looks like a default value expansion: ${VAR:-DFLT}. First time I tried this I stared at it for quite a while before a light came on as to how to do it (without using a variable [see below]):
  str=abcdefgh
echo ${str:$((-3)):2}
which outputs the desired value "fg". The "$((...))" causes bash to treat the value as an arithmetic expansion (ie a number). Another slightly longer way of doing this is:
  str=abcdefgh
i=-3
echo ${str:$i:2}

The final form of parameter expansion I want to mention is one which simply expands to the length of the variable's value, its form is ${#VAR}. So for example:

  str=abcdef
echo ${#str}
outputs "6".

Using these forms of parameter expansion in your shell scripts can simplify and shorten your scripts. These are not the only forms of parameter expansion that bash supports but they're the ones that I've found most useful over time. For more information see the "Parameter Expansion" section of the bash man page.

p.s. Note that all of the above forms of parameter expansion also work with bash's Special parameters: "$$", "$0", "$1", etc.

Tuesday, January 16, 2007

函数的递归调用与分治策略


函数的递归调用与分治策略

 

 

递 归方法是算法和程序设计中的一种重要技术。递归方法即通过函数或过程调用自身将问题转化为本质相同但规模较小的子问题。递归方法具有易于描述和理解、证明 简单等优点,在动态规划、贪心算法、回溯法等诸多算法中都有着极为广泛的应用,是许多复杂算法的基础。递归方法中所使用的"分而治之"的策略也称分治策 略。

递归方法的构造

构造递归方法 的关键在于建立递归关系。这里的递归关系可以是递归描述的,也可以是递推描述的。下面由一个求n的阶乘的程序为例,总结出构造递归方法的一般步骤。

[1]从键盘输入正整数 N0<=N<=20 ),输出N!

[ 分析]N! 的计算是一个典型的递归问题。使用递归方法来描述程序,十分简单且易于理解。

[ 步骤1]描述递归关系 递归关系是这样的一种关系。设 {U1,U2,U3,,Un}是一个序列,如果从某一项 k开始,Un 和它之前的若干项之间存在一种只与n有关的关系,这便称为递归关系。

注意到,当N>=1 时,N!=N*(N-1)!N=1时, 0!=1),这就是一种递归关系。对于特定的K! ,它只与K (K-1)!有关。

[ 步骤2]确定递归边界 在步骤1 的递归关系中,对大于k Un的求解将最终归结为对Uk 的求解。这里的Uk称为递归边界(或递归出口)。在本例中, 递归边界为k=0,即 0!=1 对于任意给定的N!,程序将最终求解到 0!

确定递归边界十分重要,如果没有确定递归边界,将导致程序无限递归而引起死循环。例如以下程序:

#include <iostream.h>

int f(int x){

  return(f(x-1));

}

main(){

  cout<<f(10);

}

它没有规定递归边界,运行时将无限循环,会导致错误。

[ 步骤3]写出递归函数并译为代码 将步骤 1和步骤2中的递归关系与边界统一起来用数学语言来表示,即

 

      N*(N-1)! N>=1

n!=

      1        N=0

再将这种关系翻译为代码,即一个函数:

long f(int n){

 if (n==0)

   return(1);

 else

   return(n*f(n-1));

}

[ 步骤4]完善程序 主要的递归函数已经完成,将程序依题意补充完整即可。

//ex1.cpp

#include <iostream.h>

long f(int n){

 if (n==0)

   return(1);

 else

   return(n*f(n-1));

}

main(){

 int n;

 cin>>n;

 cout<<endl<<f(n);

}

综上,得出构造一个递归方法基本步骤,即描述递归关系、确定递归边界、写出递归函数并译为代码,最后将程序完善。以下继续引用一些例子来讨论递归方法的应用。

经典递归问题

以下讨论两个十分经典的递归问题。它们的算法构造同样遵循刚刚得出的四个步骤。了解这两个问题可加深对递归方法的理解。

[ 2]Fibonacci数列(兔子繁殖)问题:已知无穷数列A ,满足:A(1)=A(2)=1 A(N)=A(N-1)+A(N-2)N>=3 )。从键盘输入N,输出 A(N)

[ 分析]递归关系十分明显,由 A(N)的表达式给出。需要注意的是本例中对于N>=3A(N)的值与 A(N-1)A(N-2)都有关。

[ 代码]

//ex2.cpp

#include <iostream.h>

long fibonacci(int x)

{

 if ( (x==1) || (x==2) )

   return(1);

 else

   return(fibonacci(x-1)+fibonacci(x-2));

}

main(){

 int n;

 cin>>n;

 cout>>endl>>fibonacci(n);

}

    [3]Hanoi塔问题。

    [ 问题描述]在霍比特人的圣庙里,有一块黄铜板,上面插着 3根宝石针(分别为A 号,B号和 C号)。在A号针上从下到上套着从大到小的 n个圆形金片。现要将 A针上的金片全部移到C针上,且仍按照原来的顺序叠置。移动的规则如下:这些金片只能在 3根针间移动,一次只能一片,且任何时候都不允许将较大的金片压在较小的上面。从键盘输入 n,要求给出移动的次数和方案。

[ 分析]由金片的个数建立递归关系。当 n=1时,只要将唯一的金片从A 移到C即可。当 n>1时,只要把较小的(n-1) 片按移动规则从A移到 B,再将剩下的最大的从A移到 C(即中间"借助" B把金片从A移到 C),再将B 上的(n-1)个金片按照规则从 B移到C(中间"借助" A)。

本题的特点在于不容易用数学语言写出具体的递归函数,但递归关系明显,仍可用递归方法求解。

[ 代码]

//ex3.cpp

#include <iostream.h>

hanoi (int n,char t1,char t2,char t3){

 if (n==1)

   cout<<"1 "<<t1<<" "<<t3<<endl;

 else

 {

  hanoi(n-1,t1,t3,t2);

  cout<<n<<" "<<t1<<" "<<t3<<endl;

  hanoi(n-1,t2,t1,t3);

 }

}

main(){

 int n;

 cout<<"Please enter the number of Hanoi :";

 cin>>n;

 cout<<"Answer:"<<endl;

 hanoi(n,'A','B','C');

}

函数递归调用的应用与分治策略

许多算法都采用了分治策略求解,而可以说分治与递归是一对孪生兄弟,它们经常同时被应用于算法的设计中。下面讨论著名的 Catalan数问题,人们在对它的研究中充分应用了分治策略。

[ 4]Catalan数问题。

[ 问题描述]一个凸多边形,通过不相交于 n边形内部的对角线,剖分为若干个三角形。求不同的剖分方案总数H(n)H(n)即为 Catalan数。例如,n=5 H(5)=5

[ 分析]Catalan 数问题有着明显的递归子问题特征。在计算Catalan数时虽然可以推导出只关于 n的一般公式,但在推导过程中却要用到递归公式。下面讨论三种不同的解法,其中第三种解法没有使用递归,它是由前两种解法推导而出的。

[ 解法1]对于多边形 V1V2Vn ,对角线V1Vii=3,4, ,n-1)将其分为两部分,一部分是i 边形,另一部分是n-i+1边形。因此,以对角线 V1Vi为一个剖分方案的剖分方案数为H(i)*H(n-i+1) 。还有一种的特殊情形,是对角线V2Vn 将其分为一个三角形V1V2Vn和一个 n-2+1边形。为了让它同样符合粗体字给出的公式,规定H(2)=1 。于是得到公式:

H(n)= H(i)*H(n-i+1) i=2,3,,n-1 ----公式(1)

H(2)=1

有了这个递归关系式,就可以用递推法或递归法解出 H(n)

[ 解法2] V1向除了V2Vn外的 n-3个顶点可作n-3条对角线。每一条对角线 V1Vi把多边形剖分成两部分,剖分方案数为 H(i)*H(n-i+2),由于Vi 可以是V3V4 Vn-1中的任一点,且V1 可换成V2 V3,…,Vn 中任一点也有同样的结果。考虑到同一条对角线在2个顶点被重复计算了一次,于是对每个由顶点和对角线确定的剖分方案都乘以 1/2,故有

H(n)=n (1/2)H(i)*H(n-i+2) i=3,4,,n-1

(1/2) 提到外面,

H(n)=n/(2*(n-3))H(i)*H(n-i+2) i=3,4,,n-1 ----公式 (2)

规定H(2)=H(3)=1 ,这是合理的。

由公式(2)H(2)=1,同样可以用递推法或递归法解出 H(n)

[ 解法3] 把公式(1)中的自变量改为 n+1,再将刚刚得出的公式(2)代入公式 (1),得到

H(n+1)= H(i)*H(n-i+2) i=2,3,,n    由公式(1)

H(n+1)=2*H(n)+ H(i)*H(n-i+2) i=3,4,,n-1     H(2)=1

H(n+1)=(4n-6)/n*H(n)    由公式(2)

H(n)=(4n-10)/(n-1)*H(n-1) ---- 公式(3)

这是一个较之前两种解法更为简单的递归公式,还可以继续简化为

H(n)=1/(n-1)*C(n-2,2n-4) ---- 公式(4)

这就不需要再使用递归算法了。然而在程序设计上,公式 (4)反而显得更加复杂,因为要计算阶乘。因此最后给出由公式(3) 作为理论依据范例程序代码。代码相当简单,这都归功于刚才的推导。如果用前两种解法中的递归关系,程序会变得复杂且容易写错。因此,有时对具体问题将递归关系公式进行必要的化简也是至关重要的

[ 代码]

//ex4.cpp

#include <iostream.h>

#define MAXN 100

long f(int x){

  if (x==3)

    return(1);

  else

    return((4*x-10)*f(x-1)/(x-1));

}

main(){

  int n;

  cout<<"\nPlease input N for a Catalan number:";

  cin>>n;

  if ( (n<=MAXN) && (n>=3) )

    cout<<"The answer is:"<<f(n);

}

本例编程时还有一个细节问题需要注意。注意函数f 中的斜体部分,按照公式(4)计算时一定要先进行乘法再进行除法运算,因为 (4*x-10)并不总能整除 (x-1),如果先进行除法则除出的小数部分将自动被舍去,从而导致得到不正确的解。

数学上许多有重要意义的计数问题都可以归结为对Catalan 数的研究。可以看到,本例中的递归关系经简化还是相当简单的。下面讨论一个递归关系略为复杂的例子。

[ 5]快速排序问题。

快速排序是程序设计中经常涉及的一种排序算法。它的最好时间复杂度为 O(nlog2n),最差为O(n2) ,是一种不稳定的排序方法(大小相同的数在排序后可能交换位置)。

[ 算法描述]快速排序的一种基本思想是:要将 n个数按由小到大排列,在待排序的n 个数中选取任一个数(在本例中取第一个),称为基准数,在每一次快速排序过程中设置两个指示器i j,对基准数左边和右边的数同时从最左( i)和最右(j)开始进行扫描( i1 递增,j 1递减),直到找到从左边开始的某个 i大于或等于基准数,从右边开始的某个j 小于或等于基准数。一旦发现这样的 ij(暂且称之为一个" 逆序对"),则把第i个数和第j个数交换位置,这样它们就不再是逆序对了,紧接着再将i递增1 j递减1如此反复,在交换过有限个逆序对后,ij将越来越靠近,最后"相遇",即 ij指向同一个数,暂且称之为 相遇数极端情况下,如果一开始就不存在逆序对,i j将直接"相遇")。相遇后就保证数列中没有逆序对了(除了在上述的极端情况下基准数和自身也算构成一个逆序对,注意粗体字给出的逆序对的定义)。继续扫描,非极端情况下,由于数列中已经没有逆序对, i递增1 (如果相遇数小于基准数)或者j递减 1(如果相遇数大于基准数)后即算完成了一趟快速排序,这时第1 到第j个数中的每个都保证小于或等于基准数,第 i到第n个数中的每个保证大于或等于基准数。此时,递归调用函数,对第 1到第 j个数和第i到第 n个数分别再进行一趟快速排序。如果在极端情况下,程序认为基准数和自身构成逆序对,则将基准数与自身交换(这其实没有作用)之后 i递增1 j递减1 (注意斜体字给出的对逆序对的处理方法),同样对第1到第 j个数和第i到第 n个数分别再进行一趟快速排序。

最后的问题就是确定递归边界。由于被排序的数列将不断被划分为两个至少含一个数的子列(因为在每趟排序最后进行递归调用函数时 i<>j),最后子列的长度将变为1 。这就是递归的边界。在程序实现是,本着"能排则排"的原则,只要第一个数小于j(或者第 i个数小于最后一个数),即进行递归。

[ 主程序(递归函数体)]

void QuickSort(RecType R[ ],int s,int t)

{

  int i=s,j=t,k;

  RecType temp;

  if (s<t)

  {

     temp=R[s] // 用区间第1 个记录作为基准

     while( i!=j) // 从两端向中间交替扫描,直至i=j;

      {

         while( j>i&&R[j].key> temp.key)

                j--;

         if(i<j)

             {

               R[i]=R[j];

               i++;

             }

           while( i<j&&R[i].key< temp.key)

                i++;

         if(i<j)

             {

               R[j]=R[i];

               j--;

             }

 

      }

   R[i]=temp;

   QuickSort(R,s,i-1);

   QuickSort(R,i+1,t);

}

}

    [6]"九宫阵"智力游戏。

[ 问题描述]一个 9×9 方阵,由9个"九宫格"组成,每个九宫格又由 3×3 9个小格子组成。请在每个空白小格子里面填上19的数字,使每个数字在每个九宫格内以及在整个九宫阵中的每行、每列上均出现一次。

1 )编程将下面图中的九宫阵补充完整。

2 )讨论是否可能给出"九宫阵"的全部解?

 

 

[分析 ]本题可利用回溯法解决,其基本思想为深度优先搜索(DFS ),这也是一种以分治策略为基础的算法。回溯法与纯粹的DFS不同的是,它在搜索过程中不断杀死不合题意的结点。这一点保证了解法的效率。

首先考虑如何得出全部解的情况。

解空间树容易构造,只需按顺序(从第一行第一个数字开始到第一行最后一个,然后第二行……,一直到最后一行最后一个数字)"尝试"填入数字即可。

为了解决这个问题,我们需要先编写一个函数check ,其原型为int check(int i,int j,int k),用于求第i 行第j列能否填上数字k 。如果可以,返回1,否则返回0 。由于我们是按顺序填入数字的,看起来一个数字后面的数字并不在判断能否填的范围内。但为了解决题中某个特解问题的方便,还是引入较为严谨的判断方法。

函数check 代码如下:

int check(int i,int j,int k){

  int l,m,pi,pj;

  //1. Check the line

  for (l=1;l<=9;l++)

    if ( (l!=j) && (a[i][l]!=0) && (a[i][l]==k) )

      return(0);

  //2. Check the column

  for (l=1;l<=9;l++)

    if ( (l!=i) && (a[l][j]!=0) && (a[l][j]==k) )

      return(0);

  //3. Check the 3x3 matrix

  //3.1 Firstly  we will have to check the parent_i(pi) and parent_j(pj)

  if (i<=3) pi=1;

  else if (i<=6) pi=4;

  else pi=7;

  if (j<=3) pj=1;

  else if (j<=6) pj=4;

  else pj=7;

  //3.2 Now we can check it

  for (l=0;l<=2;l++)

   for (m=0;m<=2;m++){

     if ( ((pi+l)!=i) && ((pj+m)!=j) )

       if ( ( a[pi+l][pj+m]!=0 ) && ( a[pi+l][pj+m]==k ) )

        return(0);

   }

  return(1);

}

结合注释很容易就能接受函数的思想,不予过多说明。

下面考虑程序最重要的部分,即递归函数。思路是这样的:假设某一格能填入某数,把这个格子看成解空间树的一个结点,由它可以扩展出 9个儿子,即下一格填什么数(由1 9逐个尝试)。对下一格,同样这样考虑。不断用函数check函数考察某一个能否填入某数,一旦函数 check返回0,则杀死这个结点。

如果能一直填到最后一个数,结点仍未被杀死,则这是一个解。

这种思想可用伪代码表示如下:

procedure backtrack(i,j,k:integer);

  if check(i,j,k)=true then

  begin

   a[i,j]=k;

   Generate_next_i_and_j;

   if i<10 then

   begin

     for l:=1 to 9 do

       backtrack(i,j,l);

end

else

  Do_Output;

a[i,j]:=0;

  end;

注意斜体的"a[i,j]:=0 "必不可少!当对某个结点(x,y)扩展的过程中,可能在扩展到 (x+m,y+n)时它的子树被完全杀死(每个结点都被杀死,亦即按照(x,y)及之前的填数方案填数,无解)。这时需要保证 (x,y)以后所填的数被重新置零,这个语句的作用即在每个结点被杀死时都将其置零

将伪代码翻译为C++ 代码:

backtrack(int i,int j,int k)

{

  int l;

   if (check(i,j,k)==1)

{

    a[i][j]=k; //Fill in the okay solution

    //Generate next i,j

    if (j<9) j++;

      else { i++; j=1; } //End of Generate next i,j

    if (i<10)

{

        for (l=1;l<=9;l++)

       backtrack(i,j,l);

     }

    else

      output();

    a[i][j]=0; /*When fails and goes upperwards, the value must be cleared*/

  }

}

函数output() 用双重循环完成输出。在主函数main()backtrack(1,1,i) 进行一个循环,i1 取到9,即可完成整个程序。运行时发现九宫格的解相当多,即使保存到文件中也不现实。这就回答了第2 个问题。

对于第1 个问题,将这个程序略加改动,即赋予全局数组a以初值,并在过程backtrack 中产生下一个ij 时跳过有初值的部分,即可将程序转化为求填有部分空缺的九宫格程序。

最后给出填充有部分空缺的九宫格的完整源代码。

#include <iostream>
using namespace std;
int a[11][11]={0};
int check(int i,int j,int k){
  int l,m,pi,pj;
  //1. Check the line
  for (l=1;l<=9;l++)
 if ( (l!=j) && (a[i][l]!=0) && (a[i][l]==k) )
   return(0);
  //2. Check the column
  for (l=1;l<=9;l++)
 if ( (l!=i) && (a[l][j]!=0) && (a[l][j]==k) )
   return(0);
  //3. Check the 3x3 matrix
  //3.1 Firstly we will have to check the parent_i(pi) and parent_j(pj)
  if (i<=3) pi=1;
  else if (i<=6) pi=4;
  else pi=7;
  if (j<=3) pj=1;
  else if (j<=6) pj=4;
  else pj=7;
  //3.2 Now we can check it
  for (l=0;l<=2;l++)
   for (m=0;m<=2;m++){
  if ( ((pi+l)!=i) && ((pj+m)!=j) )
    if ( ( a[pi+l][pj+m]!=0 ) && ( a[pi+l][pj+m]==k ) )
   return(0);
   }
  return(1);
}

 void output(){
  int i,j;
  cout<<"One solution is:"<<endl;
  for (i=1;i<=9;i++)
  {
 for (j=1;j<=9;j++)
   cout<<a[i][j]<<" ";
 cout<<endl;
  }
}

void backtrack(int i,int j,int k){
  int l;
  if (check(i,j,k)==1)
   {
 a[i][j]=k; //Fill in the okay solution
 //Generate next i,j
 do{
     if (j<9) j++;
     else { i++; j=1; }
   } while (a[i][j]!=0); //End of Generate next i,j
 if (i<10)
     {
     for (l=1;l<=9;l++)
  backtrack(i,j,l);
   }
 else
   output();
 a[i][j]=0; /*When fails and goes upperwards, the value must be cleared*/
  }
}

void init(){
  a[1][2]=9; a[1][6]=4; a[1][7]=5; a[1][9]=7;
  a[2][3]=3; a[2][5]=7; a[2][6]=9; a[2][7]=4;
  a[3][4]=3; a[3][5]=6; a[3][8]=8; a[3][9]=9;
  a[4][1]=3; a[4][4]=1;
  a[5][3]=4; a[5][8]=2; a[5][9]=3;
  a[6][2]=1; a[6][3]=2; a[6][6]=3;
  a[7][1]=8; a[7][8]=5;
  a[8][2]=6; a[8][4]=2; a[8][5]=9;
  a[9][2]=2; a[9][3]=1; a[9][7]=8;
  //memset(a,0,sizeof(a));
}

int main(){
  int i;
  for (i=1;i<=9;i++){
 init();
 backtrack(1,1,i);
  }
  system("PAUSE");
  return 0;
}

 

 递归方法在算法与数据结构中的应用无所不在,如动态规划(状态方程)、回溯法(深度优先搜索)等等,以上两例只是冰山一角。只有熟悉掌握函数递归调用的编程方法,深入理解分治策略的重要思想,才能编写出功能强大、高效简明的程序。