Passing game (recursion)

Passing game

Insert picture description here

Problem solving ideas

We can set f(i,j) as the number of ways the ball is at number j after passing i seconds.
Because the ball is at number 1 at 0 seconds , the initial value is f(0,1)=1
because the ball can only be passed from left to right. to , the recursive formula is
f [i] [j] = f [i - 1] [j - 1] + f [i - 1] [j + 1] f [i] [j] = f [i- 1][j-1]+f[i-1][j+1]f[i][j]=f[i1][j1]+f[i1][j+1 ]
But becausethey form a circle,the passing method of 1 and n is special

AC code

#include<cstdio>
using namespace std;
int n,m,f[35][35];
int main()
{
    
    
	scanf("%d%d",&n,&m);
	f[0][1]=1;//初值
 	for(int i=1;i<=m;i++)//递推
	 for(int j=1;j<=n;j++)
 	  if(j==1)f[i][j]=f[i-1][n]+f[i-1][j+1];
 	  else if(j==n)f[i][j]=f[i-1][j-1]+f[i-1][1];
 	  else f[i][j]=f[i-1][j-1]+f[i-1][j+1];
	printf("%d",f[m][1]);
	return 0;
}

Thank you

Guess you like

Origin blog.csdn.net/weixin_45524309/article/details/111401826