1

问题是什么算法可以找到填充大小为 N*M 的矩阵的可能性数量

这将包括从 1 到 N*M 的所有数字,从左到右,从上到下排序

例如:

对于 N = 2 , M = 3 数量为 4

  1. 1 2 3

    4 5 6

  2. 1 3 5

    2 4 6

  3. 1 2 5

    3 4 6

  4. 1 2 4

    3 5 6

我试图找出某种模式但没有成功,这是作业,我确实意识到在所有情况下,N*M 中的最大数字必须在 [N][M] 中,而最小的数字必须是在 [0][0] 中,非常感谢您的帮助

4

1 回答 1

2

你忘了:

1 3 4
2 5 6

c#中的代码:

    static int N = 5;
    static int M = 5;
    static int[,] Number;
    static int[] NumbersInRow;


    static int Put(int n)
    {
        if (n > N * M)
        {
            // If output of each solution is desired
            //for (int y = 0; y < N; y++)
            //{
            //    for (int x = 0; x < M; x++)
            //        Console.Write(Number[y, x] + "\t");

            //    Console.WriteLine();
            //}
            //Console.WriteLine();
            return 1;
        }

        int sum = 0;

        int numbersInLastRow = int.MaxValue;
        int currentRow = 0;
        while (currentRow < N)
        {
            int numbersInCurrentRow = NumbersInRow[currentRow];
            if (numbersInCurrentRow < numbersInLastRow && numbersInCurrentRow < M)
            {
                Number[currentRow, NumbersInRow[currentRow]] = n;
                NumbersInRow[currentRow]++;
                sum += Put(n + 1);
                NumbersInRow[currentRow]--;
                Number[currentRow, NumbersInRow[currentRow]] = 0;
            }
            numbersInLastRow = NumbersInRow[currentRow];
            currentRow++;
        }

        return sum;
    }

    static void Main(string[] args)
    {
        Number = new int[N, M];
        NumbersInRow = new int[N];
        Console.WriteLine(Put(1));
        Console.ReadLine();
    }

解释:

从 1 开始按顺序将数字放在板上。当一个数字有多个正确的位置时,递归拆分并计算所有解决方案。

在不尝试所有可能的位置/使用回溯的情况下,我们如何知道数字的正确位置?假设“-1th”行中有无​​限个数字,则可以将一个数字放在前一行有更多数字的任何非满行的第一个空位置。就是这样。这样我们就永远不会犯错。

请注意,这是对称的 - 就像您始终可以将下一个数字放入第一行(如果它未满)一样,您也可以将其放入第一列。

解决方案的数量增长极快:

2x2 - 2
3x3 - 42
4x4 - 24024
5x5 - 701149020
于 2012-12-17T16:15:27.910 回答