引自免费微信小程序:皆我百晓生
对于这两个题目,它们实际上是同一个问题,只是填充的方向不同。第一个例子是从左上到右下填充,第二个例子是从右上到左下填充。我们可以定义一个函数来解决这个问题,根据给定的行数 n 和当前的位置 (i, j) 来计算下一个数字,并更新位置。
以下是完整的 C++ 代码实现,包括两个版本,分别对应两种不同的填充方向:
#include <iostream>
// Function to calculate the next position and value in the snake pattern
void fill_snake_pattern(int n, int &i, int &j, int &value, bool increasing) {
if (increasing) {
// Increasing direction: from left to right and then down
if (j == n - 1 || i % 2 == 1 && j == 0) { // If at last column or starting a new row
++i;
if (i >= n) { // Wrap around if needed
i = 0;
--j;
}
} else {
++j;
}
} else {
// Decreasing direction: from right to left and then up
if (j == 0 || i % 2 == 0 && j == n - 1) { // If at first column or starting a new row
++i;
if (i >= n) { // Wrap around if needed
i = 0;
--j;
}
} else {
--j;
}
}
value += (increasing ? 1 : -1); // Increase or decrease value accordingly
}
int main() {
int n;
std::cin >> n;
int i = 0, j = 0; // Starting position
int value = 1; // Current value to be filled
for (int k = 0; k < n * n; ++k) {
std::cout << value << " ";
fill_snake_pattern(n, i, j, value, true); // For the first example, increase direction
// fill_snake_pattern(n, i, j, value, false); // Uncomment this line for the second example, decrease direction
}
std::cout << std::endl;
return 0;
}
这个程序首先读取输入的 n 值,然后初始化起始位置和值。接下来,它会遍历从 1 到 n*n 的所有数字,每次打印当前的值并更新位置。fill_snake_pattern 函数负责计算新的位置和值。根据 increasing 参数,我们选择增加还是减少值,以及是向右还是向左移动。
如果你想要分别看到两个示例的输出,只需在主循环内调用相应的 fill_snake_pattern 版本即可。第一个例子调用的是 fill_snake_pattern(n, i, j, value, true),第二个例子则需要取消注释 fill_snake_pattern(n, i, j, value, false) 并调用它。