【问题标题】:How to fill a two dimensional array?如何填充二维数组?
【发布时间】:2020-11-18 19:00:01
【问题描述】:

有一个 9 行 9 列(81 个元素)的二维数组。任务是以螺旋方式填充这个数组:从中心向左,然后向下,然后向右,然后向上。 Just like shown here. Notice: the numbers on the picture are indexes of elements!

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

#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;
}
}

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

【问题讨论】:

  • 提示:你从中间开始。然后你需要向左走一次,向下走一次,向右走 2 次,向上走 2 次,向左走 3 走,向下走 3 走,向右走 4 走……看到规律了吗?

标签: c++ arrays


【解决方案1】:

没有简单的方法。这里有一个算法,它会尽快改变方向,从左开始,出数组时停止:

#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;
}

【讨论】:

    猜你喜欢
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 2016-05-27
    • 2020-08-02
    • 2016-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多