C++谢尔夫斯基三角形递归 (代码非原创,仅自用)

1、核心思想:

基于二维数组,利用递归对数组进行相关赋值,最后打印输出。

#include <iostream>
#include <cmath>
#include <cstring>

using namespace std;
char triangle[2048][2048];

void draw(int depth,int posx,int posy){
    if(depth==1){
        triangle[posx][posy]='/';
        triangle[posx+1][posy]='\\';
        triangle[posx-1][posy+1]='/';
        triangle[posx+2][posy+1]='\\';
        triangle[posx][posy+1]='_';
        triangle[posx+1][posy+1]='_';
    }
    else{
        int side=pow(2,depth-1);
        draw(depth-1,posx,posy);
        draw(depth-1,posx-side,posy+side);
        draw(depth-1,posx+side,posy+side);
    }
}

void print(int depth,int posx,int posy){
    int side =pow(2,depth);
    for (int j = 1; j <=side; ++j){
         for (int i = posx-side; i <= posx+side; ++i){
            cout<<triangle[i][j];
        }
         cout<<endl;
    }

}


int main() {
    cout<<"这样的图腾大小为:";
    int n;
    cin>>n;
    memset(triangle,' ',sizeof(triangle));
    draw(n,1025,1);
    print(n,1025,1);
    return 0;
}

2、递归总结:

先把基础操作写出来,也就是分界条件depth==1,然后观察发现一个depth>1的谢尔夫斯基三角形是有3个起点的,所以这样就写好了一个递归。

还是无法准确总结的递归,还需加多加学习

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值