C++遞歸函數在圖形中的應用主要體現在以下幾個方面:
#include <iostream>
#include <vector>
#include <cmath>
void drawSierpinski(std::vector<std::vector<char>>& grid, int x, int y, int size) {
if (size == 1) {
grid[x][y] = 'X';
return;
}
int newSize = size / 2;
drawSierpinski(grid, x, y, newSize);
drawSierpinski(grid, x + newSize, y, newSize);
drawSierpinski(grid, x, y + newSize, newSize);
}
int main() {
int size = 5;
std::vector<std::vector<char>> grid(size, std::vector<char>(size, ' '));
drawSierpinski(grid, 0, 0, size);
for (const auto& row : grid) {
for (char c : row) {
std::cout << c;
}
std::cout << std::endl;
}
return 0;
}
#include <iostream>
struct TreeNode {
int value;
std::vector<TreeNode*> children;
TreeNode(int val) : value(val) {}
};
void traverseTree(TreeNode* node) {
if (node == nullptr) {
return;
}
std::cout << node->value << std::endl;
for (TreeNode* child : node->children) {
traverseTree(child);
}
}
int main() {
TreeNode* root = new TreeNode(1);
TreeNode* child1 = new TreeNode(2);
TreeNode* child2 = new TreeNode(3);
TreeNode* child3 = new TreeNode(4);
TreeNode* child4 = new TreeNode(5);
TreeNode* child5 = new TreeNode(6);
root->children.push_back(child1);
root->children.push_back(child2);
child1->children.push_back(child3);
child1->children.push_back(child4);
child2->children.push_back(child5);
traverseTree(root);
return 0;
}
#include <iostream>
int fibonacci(int n) {
if (n <= 1) {
return n;
}
int fibMinusTwo = fibonacci(n - 2);
int fibMinusOne = fibonacci(n - 1);
return fibMinusOne + fibMinusTwo;
}
int main() {
int n = 10;
std::cout << "Fibonacci("<< n << ") = " << fibonacci(n) << std::endl;
return 0;
}
這些示例展示了C++遞歸函數在圖形中的應用。通過遞歸地劃分問題并求解子問題,可以生成復雜且美麗的圖形和解決實際問題。