到达某地的路径计算

题目

从(0,0)到(m,n),每次走一步,只能向上或者向右走,有多少种路径走到(m,n)

从0 0到2 2和3 3的路径种类

#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;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值