如何填充二维数组



有一个包含9行9列(81个元素(的二维数组。任务是以螺旋的方式填充这个阵列:从中心向左,然后向下,然后向右,然后向上。如图所示。注意:图片上的数字是元素的索引!

如何做到这一点?我只知道如何用这种方式填充数组(首先填充第一行的所有列,然后填充第二行的所有栏,依此类推(:

#include <iostream>
using namespace std;
int main()
{
const int rows = 9;
const int cols = 9;
int ARR[rows][cols];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
ARR[i][j] = rand() % 10;
}
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cout << ARR[i][j] << "  ";
}
cout << endl;
}
}

那么,我该如何完成这项任务:以螺旋方式填充数组呢?

没有简单的方法。这里有一种算法,可以尽快改变方向,从左边开始,离开阵列时停止:

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
// use constexpr to have true constants
constexpr const int rows = 9;
constexpr const int cols = 9;
int ARR[rows][cols];
// Initialize the array to 0 values to detect unmodified slots
for (int (&row)[cols]: ARR) {
for (auto &val: row) {
val = 0;
}
}
// Use symbols for directions
enum Dir {
left = 0,
down,
up,
right,
} dir = left;
// Define the starting point and starting value
int x = rows / 2;
int y = cols / 2;
int val = 1;

// A flag to know when to stop
bool stop = false;
// Let's go...
for (;;) {
ARR[x][y] = val++;
switch (dir) {
case left:
y -= 1;
if (y < 0) stop = true;
else if (ARR[x+1][y] == 0) dir = down;
break;
case down:
x += 1;
if (x > rows) stop = true;
else if (ARR[x][y+1] == 0) dir = right;
break;
case right:
y += 1;
if (y >= rows) stop = true;
else if (ARR[x-1][y] == 0) dir = up;
break;
case up:
x -= 1;
if (x < 0) stop = true;
else if (ARR[x][y-1] == 0) dir = left;
}
if (stop) break;
}
// Display the values
for (int (&row)[cols]: ARR) {
for (auto val: row) {
cout << setw(3) << val;
}
cout << 'n';
}
return 0;
}

最新更新