c# - 内螺旋算法不起作用

标签 c# algorithm spiral

我有这个 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/

相关文章:

c# - 具有多种类型的通用方法

c# - 将 int 转换为 double 并四舍五入到最后一个整数

c++ - 检测凸多边形的极值点

algorithm - 图中从单一源到单一目的地的最短路径

scala - 在 Scala 中生成惰性 "spiral"

c# - 远程服务器返回错误 : (550) on upload file to FTP using FtpWebRequest

algorithm - 遮挡算法集合

matlab - 非重叠圆的螺旋

language-agnostic - Code Golf : Easter Spiral

c# - 如何将此 VB.net/C# 代码移植到 Objective-C/iOS?