如何在C++中实现矩阵内的环形移动效果?
矩阵中1的环形移动效果实现
实现逻辑
要实现环形移动效果,核心是让数字1沿着矩阵外围边界按固定路径循环移动,具体步骤如下:
- 拆分环形路径为4段连续轨迹:
- 顶部行:从左到右遍历所有列
- 右侧列:从上到下遍历除顶部行外的所有行
- 底部行:从右到左遍历除右侧列外的所有列
- 左侧列:从下到上遍历除底部行和顶部行外的所有行
- 维护当前1的位置坐标,每次移动时先将当前位置重置为0,再根据路径更新坐标并设为1
- 使用精准的延时控制保证移动流畅性,避免界面无效闪烁
修改后的代码
#include <iostream> #include <chrono> #include <thread> #define SIZE 3 // 矩阵大小,可按需调整 int field[SIZE][SIZE] = {0}; // 显示矩阵 void showField() { system("cls"); // Windows用cls,Linux/macOS替换为clear for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { std::cout << field[i][j] << " "; } std::cout << std::endl; } } int main() { // 初始化初始位置(顶部行第一个元素) int currRow = 0, currCol = 0; field[currRow][currCol] = 1; showField(); while (true) { // 顶部行从左到右 while (currCol < SIZE - 1) { field[currRow][currCol] = 0; currCol++; field[currRow][currCol] = 1; showField(); std::this_thread::sleep_for(std::chrono::seconds(1)); } // 右侧列从上到下 while (currRow < SIZE - 1) { field[currRow][currCol] = 0; currRow++; field[currRow][currCol] = 1; showField(); std::this_thread::sleep_for(std::chrono::seconds(1)); } // 底部行从右到左 while (currCol > 0) { field[currRow][currCol] = 0; currCol--; field[currRow][currCol] = 1; showField(); std::this_thread::sleep_for(std::chrono::seconds(1)); } // 左侧列从下到上(回到顶部行前停止) while (currRow > 1) { field[currRow][currCol] = 0; currRow--; field[currRow][currCol] = 1; showField(); std::this_thread::sleep_for(std::chrono::seconds(1)); } } return 0; }
代码说明
- 用
std::this_thread::sleep_for替代原循环延时,更精准且避免无效刷新 - 拆分四个方向的循环,清晰对应环形路径的四个边
- 移除原代码中不规范的
goto语句,改用嵌套循环实现持续移动 - 用
SIZE宏统一定义矩阵大小,方便后续调整
内容的提问来源于stack exchange,提问作者Hayk
相关产品推荐
相关产品推荐

