【问题标题】:All solutions for a matrix sorting矩阵排序的所有解决方案
【发布时间】:2013-07-06 09:22:52
【问题描述】:

这个问题跟在这个问题后面:How to sort a 2D Matrix

在上一个问题中,OP询问如何对矩阵进行排序,例如行和列排序(M[i][j]

我的问题是:什么算法可以为我们提供这个问题的所有解决方案?一个明显的解决方案是回溯算法,但我相信我们可以做得更好......

同一个数组的解法示例:

0 0 1 2 
2 2 3 3 
3 5 5 6 
6 6 6 6 
7 7 9 9 

还有:

0 2 3 6
0 2 5 6
1 3 5 6
2 3 6 6
7 7 9 9

还有:

0 2 3 6
0 2 5 6
1 3 5 7
2 3 6 7
6 6 9 9

还有:

0 2 3 6
0 2 5 6
1 3 5 7
2 3 6 9
6 6 7 9

等等……

【问题讨论】:

    标签: algorithm sorting


    【解决方案1】:

    这将是最有效的生成解决方案,但是由于有很多方法,我提出了以下算法(它是伪 C++)

    int mat[n][m] = {-1}; // initialize all cells with -1
    int sortedArray[n * m]; // the sorted array of all numbers, increasing order
    
    void generateAllSolutions(set<pair<int, int> > front, int depth) {
        if (depth == n * m) {
            printMatrix();
            return;
        }
    
        for (pair<int, int> cell : front) {
             mat[cell.first][cell.second] = sortedArray[depth];
             newFront = front;
             newFront.remove(cell);
             if (cell.first < n - 1 &&
                  (cell.second == 0 || mat[cell.first + 1][cell.second - 1] != -1)) {
                 newFront.add(<cell.first + 1, cell.second>);
             }
             if (cell.second < m - 1 &&
                  (cell.first == 0 || mat[cell.first - 1][cell.second + 1] != -1))
                 newFront.add(<cell.first, cell.second + 1>);
             }
             generateAllSolutions(newFront, depth + 1);
             mat[cell.first][cell.second] = -1; // backing the track
        }
    }
    
    void solve() {
       set<pair<int, int> > front = {<0, 0>}; // front initialized to upper left cell
       generateAllSolutions(front, 0);
    }
    

    我正在做的是保留所有可能候选下一个最小数字的单元格的“前面”。这些基本上是所有其上、左邻居已经用较小数字填充的单元格。

    因为我提出的算法可以优化为使用所有解决方案中所有单元格数量的数量级的操作,这对于您的任务来说应该是最佳的可能解决方案性能。

    我想知道如果你只打算计算所有可能的解决方案是否有任何聪明的解决方案(我可以立即设计一个量级为 O(min(mn, nm支持>))

    【讨论】:

    • 如果元素都是不同的,那么我相信您可以使用hook length formula 计算解决方案,但我不确定如何将其扩展到有重复条目的情况。
    【解决方案2】:

    为了改进回溯算法的一些修剪:

    注意,例如在一个 5*4 的排序矩阵 M 中,

    M[0][0] 是所有元素集合S 中的最小值,M[4][3] 是最大值。

    M[0][1]M[1][0]S - ({M[0][0]}∪{M[4][3]}) 中的两个最小值,而

    M[3][3]M[4][2] 是其中的两个最大值。

    只有 2*2 个案例。

    同样,M[1][1] 是最小值,M[3][2]S - {M[0][0],M[4][3],M[0][1] , M[1][0],M[3][3] , M[4][2]} 中的最大值,这是确定的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-01
      • 1970-01-01
      • 2011-08-15
      • 2022-11-16
      • 1970-01-01
      • 1970-01-01
      • 2019-10-18
      • 2020-04-09
      相关资源
      最近更新 更多