0

そこで、C# を使用してスパイラル マトリックスを作成しています。

らせん配列は、最初の N^2 個の自然数の正方配列であり、配列の端から内側にらせん状に進むにつれて数値が順次増加します。

例えば:

ここに画像の説明を入力

アルゴリズムを使用してこれを行うことになっていますが、最終結果は次のようになります。

ここに画像の説明を入力 ここに画像の説明を入力

私のコードは以下の通りです:

    private static void FillMatrix (int[ , ] matrix, int n)
    {
        int positionX = 0;
        int positionY = 0;

        int direction = 0; // The initial direction is "right"
        int stepsCount = n - 1; // stepsCount decrements after 3/2/2/2/2...
        int stepPosition = 0; // 0 steps already performed
        int counter = 1; // counter increments after every turn

        for (int i = 1; i < n * n; i++)
        {
            matrix[positionY, positionX] = i;

            //moving logic:

            if (stepPosition < stepsCount)
            {
                stepPosition++;
            }
            else
            {
                counter++;
                stepPosition = 1;

                if (counter <= 3)
                {
                    direction = (direction + 1) % 4;
                }

                else if (counter % 2 != 0 && counter >= 5 || counter == 4)
                {
                    stepsCount = stepsCount - 1;
                    direction = (direction + 1) % 4;
                }
            }


            // Move to the next cell in the current direction
            switch (direction)
            {
                case 0:
                    // right
                    positionX++;
                    break;
                case 1:
                    // down
                    positionY++;
                    break;
                case 2:
                    // left
                    positionX--;
                    break;
                case 3:
                    // up
                    positionY--;
                    break;
            }
        }
    }

    private static void PrintMatrix (int[ , ] matrix, int n)
    {
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                Console.Write("{0,3}", matrix[i, j]);
            }
            Console.WriteLine();
        }
    }

    static void Main(string[] args)
    {
        int n;

        Console.WriteLine("Please enter N: ");
        bool checkN = int.TryParse(Console.ReadLine(), out n);

        if (checkN)
        {
            int[,] spiralMatrix = new int[n,n];

            FillMatrix(spiralMatrix, n);

            PrintMatrix(spiralMatrix, n);
        }

        Console.ReadKey();
    }
}

}

どんな助けでも大歓迎です!

4

2 に答える 2