使用 std:sort 在本地排序

Using std:sort to sort locally

本文关键字:排序 sort std 使用      更新时间:2023-10-16

我正在制作一个Soduku求解器,所以我需要测试行,列和正方形的合法性。我有每个功能要做。

bool Board::isRowLegal(int row){
    sort(theBoard[row].begin(), theBoard[row].end());
    for(int i = 1; i < theBoard[row].size() - 1; ++i){
        if(theBoard[row][i] != 0){
            if(theBoard[row][i] == theBoard[row][i + 1]){
                return false;           
            }   
        }
    }
    return true;
}
bool Board::isColumnLegal(int column){
    vector<int> currentColumn;
    int current = 0;
    for(int i = 1; i < theBoard.size(); ++i){
        currentColumn.push_back(theBoard[i][column]);
    }
    sort(currentColumn.begin(), currentColumn.end());
    for(int j = 0; j < currentColumn.size() - 1; ++j){
        if(currentColumn[j] != 0){
            if(currentColumn[j] == currentColumn[j + 1]){
                return false;           
            }   
        }
    }
    return true;
}
bool Board::isPanelLegal(int rowStart, int colStart){
    vector<int> currentPanel;
    for(int i = rowStart; i < rowStart + THREE; ++i){
        for(int j = colStart; j < colStart + THREE; ++j){
            currentPanel.push_back(theBoard[i][j]);
        }
    }
    sort(currentPanel.begin(), currentPanel.end());
    for(int k = 0; k < currentPanel.size() - 1; ++k){
        if(currentPanel[k] != ZERO){
            if(currentPanel[k] == currentPanel[k + 1]){
                return false;           
            }   
        }
    }   
    return true;
}

我对电路板进行排序,以便可以测试重复项。当我的程序命中isColumnLegal函数时,我遇到了问题。似乎板的向量已经与其行相对应进行了排序,这意味着我的列函数无法检测到列的合法性,因为这些行不再对应。所以我的问题是,有没有办法使用 std::sort 函数并在本地排序,而无需将vector复制到另一个vector?可以想象,这个程序已经效率低下了,我不想再通过复制向量来制作它了。我知道这只是 10 x 10 vectorint但仍然如此。

创建一个包含 9 个bool元素的数组,初始化为 false。 遍历向量,将找到的任何数字的索引(减一)设置为 true。 如果在此过程中遇到已设置为 true 的元素,则该行无效。

bool present[9] = {};
for (auto const i : theBoard[row])
{
    if (i != 0)
    {
        if (present[i-1])
            return false;
        present[i-1] = true;
    }
}
return true;