- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我想顺时针打印一个二维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/
我已经很长时间没有使用数学了,这应该是一个简单的问题。 假设我有两个点 A:(1, 0) 和 B:(1, -1)。 我想使用一个程序(Python 或任何编程语言)来计算 A、原点 (0, 0) 和
我有一个用点表示的凸多边形。点由x 坐标数组 和y 坐标数组 表示。 例如: X = {6, 1, 5, 0, 3} Y = {4, 0, 0, 4, 6} 如何按顺时针排序这些点?点数并不总是相同,
我正在开发一个项目,使用这段代码将一个元素拖到另一个圆形元素周围:http://jsfiddle.net/sandeeprajoria/x5APH/11/ function rotateAnn
我有一个二维矩阵 M[N][N],我需要将其逆时针旋转 90 度。我已经看到很多顺时针旋转的答案,但我找不到逆时针旋转的答案。这两个操作有多相似? 最佳答案 如果您反转每一行的顺序,然后顺时针旋转以相
对于我不会涉及的上下文,我需要两个本质上互为倒数的函数。 angle_to() 应该返回钟针从 0° 到连接 p1 和 p2 的线所必须转动的度数>(即 p1 是旋转中心),其中 p1 和 p2 都是
我是一名优秀的程序员,十分优秀!