NPE 认为循环缓冲区是最佳解决方案是正确的。这是一个使用 C++ 的循环缓冲区的简单示例。注意模数运算符而不是if
测试。
#include <iostream>
int main(int argc, char **argv)
{
int front = 4;
int back = 0;
int length = 10;
int snake[10] = { 1,1,1,1,1,0,0,0,0,0 };
for (int i = 0; i < length * 3; i++)
{
for (int j = 0; j < length; j++)
std::cout << snake[j] << " ";
std::cout << std::endl;
snake[back] = 0;
front = (front + 1) % length;
back = (back + 1) % length;
snake[front] = 1;
}
}
输出:
1 1 1 1 1 0 0 0 0 0
0 1 1 1 1 1 0 0 0 0
0 0 1 1 1 1 1 0 0 0
0 0 0 1 1 1 1 1 0 0
0 0 0 0 1 1 1 1 1 0
0 0 0 0 0 1 1 1 1 1
1 0 0 0 0 0 1 1 1 1
1 1 0 0 0 0 0 1 1 1
1 1 1 0 0 0 0 0 1 1
1 1 1 1 0 0 0 0 0 1
1 1 1 1 1 0 0 0 0 0
0 1 1 1 1 1 0 0 0 0
0 0 1 1 1 1 1 0 0 0
0 0 0 1 1 1 1 1 0 0
0 0 0 0 1 1 1 1 1 0
0 0 0 0 0 1 1 1 1 1
1 0 0 0 0 0 1 1 1 1
1 1 0 0 0 0 0 1 1 1
1 1 1 0 0 0 0 0 1 1
1 1 1 1 0 0 0 0 0 1
1 1 1 1 1 0 0 0 0 0
0 1 1 1 1 1 0 0 0 0
0 0 1 1 1 1 1 0 0 0
0 0 0 1 1 1 1 1 0 0
0 0 0 0 1 1 1 1 1 0
0 0 0 0 0 1 1 1 1 1
1 0 0 0 0 0 1 1 1 1
1 1 0 0 0 0 0 1 1 1
1 1 1 0 0 0 0 0 1 1
1 1 1 1 0 0 0 0 0 1
请注意输出如何很好地展示了蛇在缓冲区中“移动”。