gpt4 book ai didi

c++ - 在二维数组周围做一个圆圈

转载 作者:行者123 更新时间:2023-12-04 20:19:45 25 4
gpt4 key购买 nike

我在二维数组内转弯以螺旋输出元素时遇到问题。我试过这段代码,但它输出的元素不够,我试图在循环之外做一些 if 语句来覆盖通用算法不输出的所有情况。你能帮忙建议一些管理正确输出的方法吗?

代码

#include <iostream>  
#include <algorithm>
//#include <cmath>

using namespace std;

int main() {
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);

int r, c;
cin >> r >> c;
int r_beg = 0, r_end = r - 1, c_beg = 0, c_end = c - 1;

int **m = new int*[r];

for (int i = 0; i < r; i++)
{
m[i] = new int[c];
for (int j = 0; j < c; j++)
{
cin >> m[i][j];
}
}

for (int runs = min(r, c) / 2; runs--;) {

for (int i = c_beg; i < c_end; i++)
cout << m[r_beg][i] << " ";

for (int i = r_beg; i < r_end; i++)
cout << m[i][c_end] << " ";

for (int i = c_end; i > c_beg; i--)
cout << m[r_end][i] << " ";

for (int i = r_end; i > r_beg; i--)
cout << m[i][c_beg] << " ";

r_beg++;
c_beg++;
r_end--;
c_end--;
}


if (r <= c && c_beg <= c_end) {
for (int i = c_beg; i <= c_end; i++)
cout << m[r_end][i] << " ";
}
else if (r >= c && r_beg <= r_end) {
for (int i = r_beg; i <= r_end; i++)
cout << m[i][c_end] << " ";
}

for (int i = 0; i < r; i++)
delete[] m[i];
delete[] m;

return 0;
}

例子:

输入:
3 3
1 2 3
4 5 6
7 8 9

输出: 1 2 3 6 9 8 7 4 5
如果您有例如 3x10 矩阵。它不输出。

输入:
3 

7

1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21

输出:应该达到 13,但它停在 8。

最佳答案

如所示,代码向中心循环,直到两个维度中较小的一个被消耗掉。但是,如果那个较小的维度具有奇数大小,那么中央行或列的部分分别没有被打印出来。你可以在你的外循环之后用一些特殊的案例处理来覆盖那个:

for (int runs = std::min(r, c) / 2; runs--;)
{
// ...
}

if(c < r)
{
if(c & 1)
{
for (int i = r_beg; i <= r_end; i++)
// ^ (!)
// don't forget to print last element: there's no second loop
// that would print the corner element a second time now!
std::cout << m[i][c_end] << " ";
}
}
else
{
// handles the square matrix case as well

if(r & 1)
{
for (int i = c_beg; i <= c_end; i++)
std::cout << m[r_beg][i] << " ";
}
}

关于c++ - 在二维数组周围做一个圆圈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58624473/

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