题目
从(0,0)到(m,n),每次走一步,只能向上或者向右走,有多少种路径走到(m,n)
#include<stdio.h>
#include<stdlib.h>
int numroute(int m,int n)
{
int w;
if ((m == 0) && (n == 0)) w = 0;
else if ((n == 1&& m == 0) || (m == 1&&n == 0)) w = 1;
else if (n == 0) w = numroute(m - 1, n);
else if (m == 0) w = numroute(m, n - 1);
else {
w = numroute(m, n - 1) + numroute(m - 1, n);
}
return w;
}
int main() {
int m, n, w;
scanf_s("%d %d", &m, &n);
w = numroute(m, n);
printf("the number of route is:%d\n", w);
return 0;
}
打印路径
若需打印路径,则需记录某一路径下到达某点每步走过的每个点的坐标,其实不管递归哪一条路径,step=a+b。
每条递归的路径中递归一次,step+1次,后面每次递归,nd[step+1].x和nd[step+1].y重新赋值,打印中以step为某一路途中每一点的索引
#include<stdio.h>
#include<stdlib.h>
typedef struct node //建立结构体节点记录每步走过的节点
{
int x, y;
}node;
int cnt;
node nd[100];
int ff(int a, int b, int x, int y, int step)
{
int i;
if (a == x && b == y) //当(x,y)到(a,b)时
{
cnt++; //某种路径到达终点后count++
for (i = 0; i < step; i++) //到达终点后打印之前走过的每一步
{
printf("(%d,%d) -> ", nd[i].x, nd[i].y); //打印第i步的节点坐标
}
printf("(%d,%d)\n", nd[i].x, nd[i].y); //打印最后一个节点
return 0;
}
else //未到达则向右走或向上走
{
if (x < a && y <= b) //未到第a列则可向右走
{
nd[step + 1].x = x + 1; //记录每步走过的点坐标
nd[step + 1].y = y;
ff(a, b, x + 1, y, step + 1); //递归计算从(x+1,y)到(a,b)的路径种类
}
if (y < b && x <= a) //未到第b行则可向上走
{
nd[step + 1].x = x; //记录每步走过的点坐标
nd[step + 1].y = y + 1;
ff(a, b, x, y + 1, step + 1); //递归计算从(x,y+1)到(a,b)的路径种类
}
}
return 0;
}
int main()
{
int a, b;
while (scanf_s("%d%d", &a, &b) != EOF)
{
cnt = 0;
nd[0].x = nd[0].y = 0; //(x,y)=(0,0)
ff(a, b, 0, 0, 0);
printf("the number of route is:%d\n", cnt);
}
return 0;
}