这将是最有效的生成解决方案,但是由于有很多方法,我提出了以下算法(它是伪 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支持>))