【问题标题】:Fill matrix with specific conditions用特定条件填充矩阵
【发布时间】:2012-12-04 17:02:06
【问题描述】:

问题是什么算法可以找到填充大小为 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] 中,非常感谢您的帮助

【问题讨论】:

    标签: algorithm matrix pseudocode


    【解决方案1】:

    你忘了:

    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
    

    【讨论】:

      猜你喜欢
      • 2021-07-29
      • 2019-01-13
      • 2018-12-17
      • 1970-01-01
      • 1970-01-01
      • 2018-09-20
      • 1970-01-01
      • 2021-07-16
      • 1970-01-01
      相关资源
      最近更新 更多