我有这个 C# 代码来以向内螺旋的方式迭代网格,如下所示:
1 2 3
8 9 4
7 6 5
这是代码,但它有问题,由于某种原因,计算时间比预期长得多。有谁知道为什么会发生这种情况?
static void create_spiral_img(int width, int height)
{
Bitmap img = new Bitmap(width, height);
Graphics graph = Graphics.FromImage(img);
int x = 0;
int y = 0;
int size = width * height;
int max = size;
int count = 1;
int i, j;
while (size > 0)
{
for (i = y; i <= y + size - 1; i++)
{
draw_pixel(count++, x, i, graph);
}
for (j = x + 1; j <= x + size - 1; j++)
{
draw_pixel(count++, j, y + size - 1, graph);
}
for (i = y + size - 2; i >= y; i--)
{
draw_pixel(count++, x + size - 1, i, graph);
}
for (i = x + size - 2; i >= x + 1; i--)
{
draw_pixel(count++, i, y, graph);
}
x = x + 1;
y = y + 1;
size = size - 2;
Console.Write(100 * ((float)(count) / (float)max) + "% ");
}
graph.Dispose();
img.Save("./" + width + "x" + height + "_spiril.png", System.Drawing.Imaging.ImageFormat.Png);
img.Dispose();
}
最佳答案
假设是一个正方形(宽度=高度),看起来您有一个 O(x^4) 实现 - 这将非常慢。
我建议尝试将其降低到 O(x^2)。不要以螺旋方式绘制它,而是重写算法以将其绘制为矩形 - 也就是说,按行和列计算每个像素应该是什么。
关于c# - 内螺旋算法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15235083/