创建向外螺 [英] Creating outward spiral
问题描述
我一直在想这件事,我只是不能想办法填补与向外的螺旋矩阵,这样我可以做到以下几点:
I've been thinking about this and I just can't think of a way to fill in a matrix with an outward spiral, so that I can do the following:
启用此: 1 2 3 4 5 ... N
Turn this: 1 2 3 4 5 ... n
要
21 22 23 24 25 26
20 07 08 09 10 27
19 06 01 02 11 28
18 05 04 03 12 29
17 16 15 14 13 30
...n
我的问题是算法本身,但如果不是伪code可以帮助C ++,那会更好。
My problem is the algorithm itself, but if instead of pseudocode you can help with C++, that'd be better.
这是一些code我写了测试的东西,但我真的不知道我怎么能去做到这一点。
This is some code I wrote to test things out, but I really don't know how I can go about to do this.
#include <stdio.h>
#include <string>
using namespace std;
int main() {
//int n = 5;
int spiral[5][6];
for (int i = 0; i < 5; i++)
for (int u = 0; u < 6; u++)
spiral[i][u] = 0;
spiral[2][2] = 1;
string direction = "right";
for (int i = 2; i < 5; i++) {
for (int u = 2; u < 6; u++) {
if (direction == "right") {
spiral[i][u + 1] = spiral[i][u] + 1;
direction = "down";
}
}
}
for (int i = 0; i < 5; i++) {
for (int u = 0; u < 6; u++) {
printf("%02d ", spiral[i][u]);
}
printf("\n");
}
return 0;
}
感谢您!
推荐答案
您可以观察,也有类似的广场,在左下角位置的最低值,那么会向上,右,下,左
You can make the observation that there are similar squares with the lowest value in the bottom-left position then going upwards, right, down and left.
您可以使用它来创建一个这样的功能:
You can use this to create such a function:
template <typename Array>
void spiral_square(Array& a, int x, int y, int side, int& value)
{
int mx = x+side-1, my=y+side-1;
for (int i = 1; i <= side-1; ++i) a[my-i][x] = value++;
for (int i = 1; i <= side-1; ++i) a[y][x+i] = value++;
for (int i = 1; i <= side-1; ++i) a[y+i][mx] = value++;
for (int i = 1; i <= side-1; ++i) a[my][mx-i] = value++;
}
请参阅它在行动: http://ideone.com/9iL1F
这篇关于创建向外螺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!