递归(recursion):程序调用自身的编程技巧。
递归满足2个条件:
1)有重复运行的过程(调用自身)
2)有跳出重复运行过程的条件(递归出口)
一、阶乘:
#include <iostream> using namespace std; int recursive(int i) { int sum = 0; if (0 == i) return (1); else sum = i * recursive(i-1); return sum; } int main() { int n,ans; cout<<"请输入一个整数n:"<<endl; cin>>n; ans=recursive(n); cout<<n<<"的阶乘为:"<<ans<<endl; return 0; }
二、汉诺塔
#include<stdio.h> void move(int n,char a,char b,char c) { if(n==1) printf("\t%c->%c\n",a,c); //当n仅仅有1个的时候直接从a移动到c else { move(n-1,a,c,b); //第n-1个要从a通过c移动到b printf("\t%c->%c\n",a,c); move(n-1,b,a,c); //n-1个移动过来之后b变開始盘,b通过a移动到c,这边非常难理解 } } main() { int n; printf("请输入要移动的块数:"); scanf("%d",&n); move(n,'a','b','c'); }
三、①斐波那契数
#include <iostream> using namespace std; int Fib(int n) { if (n == 0) return 0; if (n == 1) return 1; if (n > 1) return Fib(n-1) + Fib(n-2); } int main() { int n,ans; cout<<"请输入一个整数n:"<<endl; cin>>n; ans=Fib(n); cout<<n<<"的斐波那契数为:"<<ans<<endl; return 0; }
三、②斐波那契数
#include <iostream> using namespace std; long long fibonacci(int n) { if(n <= 2) { return 1; } int i; long long a = 1, b = 1; for(i = 3; i <= n; ++i) { b = a + b; a = b - a; } return b; } int main() { int n,ans; cout<<"请输入一个整数n:"<<endl; cin>>n; ans=fibonacci(n); cout<<n<<"的斐波那契数为:"<<ans<<endl; return 0; }
四、迷宫问题(深搜)
#include<iostream> using namespace std; #define min(a,b) a < b ? a : b int Map[9][9] = {1,1,1,1,1,1,1,1,1, 1,0,0,1,0,0,1,0,1, 1,0,0,1,1,0,0,0,1, 1,0,1,0,1,1,0,1,1, 1,0,0,0,0,1,0,0,1, 1,1,0,1,0,1,0,0,1, 1,1,0,1,0,1,0,0,1, 1,1,0,1,0,0,0,0,1, 1,1,1,1,1,1,1,1,1,}; int a,b,c,d,num; void dfs(int x,int y,int s){ if(Map[x][y]) return; if(x == c && y == d){ num = min(s,num); return; } s++; Map[x][y] = 1; dfs(x - 1,y,s); dfs(x + 1,y,s); dfs(x,y - 1,s); dfs(x,y + 1,s); Map[x][y] = 0; } int main(){ int n; cin >> n; while(n--){ num = 10000; cin >> a >> b >> c >> d; dfs(a,b,0); cout << num << endl; } return 0; }
四、迷宫问题(广搜)
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<queue> using namespace std; int dir[4][2]= {1,0,-1,0,0,1,0,-1}; struct point{ int x,y,step; }; int bfs(point s,point e,int map[9][9]){ queue<point>tp;//自己定义类型的队列 int i; point t;//保存当前坐标 ,暂时变量 //s表示之前 //e表示目标 s.step=0;//保存步数 map[s.x][s.y]=1;//标记此处已经走过 tp.push(s);//初始化队列 ,s中(x,y)初始为起始坐标。step = 0 while(!tp.empty()){//循环直至队列为空 s=tp.front();//每次循环s都等于队首 tp.pop();//删除队首 if(s.x==e.x&&s.y==e.y)//假设当前坐标与目标坐标相等 return s.step; //返回当前的步数 //遍历四个不同的方向 //假设是通道(0),即添加步数 for(int i=0; i<4; i++){ t.x=s.x+dir[i][0]; t.y=s.y+dir[i][1]; if(map[t.x][t.y]==0){//假设是通道 t.step=s.step+1; map[t.x][t.y]=1;//标记此处已经走过。及标记为墙 tp.push(t); } } } } int main(){ int t; scanf("%d",&t); while(t--){ point s,e; int map[9][9]= {1,1,1,1,1,1,1,1,1, 1,0,0,1,0,0,1,0,1, 1,0,0,1,1,0,0,0,1, 1,0,1,0,1,1,0,1,1, 1,0,0,0,0,1,0,0,1, 1,1,0,1,0,1,0,0,1, 1,1,0,1,0,1,0,0,1, 1,1,0,1,0,0,0,0,1, 1,1,1,1,1,1,1,1,1,}; scanf("%d%d%d%d",&s.x,&s.y,&e.x,&e.y); printf("%d\n",bfs(s,e,map)); } return 0; }
时间: 2024-10-02 14:45:04