gpt4 book ai didi

c++ - 如何顺时针打印二维矩阵?

转载 作者:搜寻专家 更新时间:2023-10-31 02:10:44 28 4
gpt4 key购买 nike

我想顺时针打印一个二维N x M矩阵,例如:假设输入矩阵是

 1  2  3  4
5 6 7 8
9 10 11 12
13 14 15 16

然后输出看起来像这样:

1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10

这是我在 C++ 中的实现:

#include <cstdio>    

void circle_print(int a[][4], int lx, int ly, int rx, int ry)
{
if (lx > rx || ly > ry)
return;

int x = lx, y = ly;

for (; y < ry; y++)
printf("%d\n", a[x][y]);

for (; x < rx; x++)
printf("%d\n", a[x][y]);

for (; y > ly; y--)
printf("%d\n", a[x][y]);

for (; x > lx; x--)
printf("%d\n", a[x][y]);

circle_print(a, lx + 1, ly + 1, rx - 1, ry - 1);
}


int main(int argc, char const *argv[])
{
int a[][4] = {
{ 1, 2, 3, 4},
{ 5, 6, 7, 8},
{ 9, 10, 11, 12},
{13, 14, 15, 16},
{17, 18, 19, 20},
{21, 22, 23, 24},
};

circle_print(a, 0, 0, 5, 3);

return 0;
}

N > 1 的情况下,结果是好的。但是,当 N = 1 时,即矩阵 a 只是 { 1, 2, 3, 4 },输出为 1 2 3 4 3 2 并且这显然不是预期的。

如何以优雅的方式修改我的代码以解决此问题?

最佳答案

有点不同的方法,没有四个循环和递归,但有 O(n*m) 额外的内存。我认为它不太容易出错。

void circle_print(const vector<vector<int>>& a)
{
const int step[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int dir = 0;
int n = a.size();
int m = a[0].size();

vector<vector<int>> was(n, vector<int>(m, 0));

int x = 0, y = 0;
for (int i = 0; i < n*m; ++i) {
printf("%d ", a[x][y]);
was[x][y] = 1;

int newx = x + step[dir][0];
int newy = y + step[dir][1];
if (newx < 0 || newy < 0 || newx == n || newy == m || was[newx][newy] == 1) {
dir = (dir + 1) % 4;
}

x += step[dir][0];
y += step[dir][1];
}
}


int main(int argc, char const *argv[])
{
vector<vector<int>> a = {
{ 1, 2, 3, 4},
{ 5, 6, 7, 8},
{ 9, 10, 11, 12},
{13, 14, 15, 16},
{17, 18, 19, 20},
{21, 22, 23, 24},
};

circle_print(a);

return 0;
}

可运行版本:http://ideone.com/Qq9VYf

关于c++ - 如何顺时针打印二维矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44798310/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com