Sudoku使用回溯算法求解

时间:2013-01-24 20:01:06

标签: c recursion backtracking

我在youtube上看过这个讲座:http://www.youtube.com/watch?v=p-gpaIGRCQI 并且有我写的代码:

int _Solve(int iRow, int iCol)
{
    if (iRow == 9) return 1;

    if (arrBoard[iRow][iCol])
    {
        iRow = (iCol == 8) ? iRow + 1 : iRow;
        iCol = (iCol == 8) ? 0 : iCol + 1;

        if(_Solve(iRow, iCol)) return 1;
        return 0;
    }

    int iNewNum, iOldRow, iOldCol;
    for (iNewNum = 1; iNewNum <= SIZE; iNewNum++)
    {
        if (IsValid(iNewNum, iRow, iCol))
        {
            arrBoard[iRow][iCol] = iNewNum;

            iOldRow = iRow; iOldCol = iCol;
            iRow = (iCol == 8) ? iRow + 1 : iRow;
            iCol = (iCol == 8) ? 0 : iCol + 1;

            if (_Solve(iRow, iCol)) return 1;

            iRow = iOldRow; iCol = iOldCol;
            arrBoard[iRow][iCol] = 0;
        }
    }
    return 0;
}

但它不起作用,在我打印我的arrBoard之后,我得到它每个空单元格显示零值.. 这是将拼图放入arrBoard并显示它的函数(arrBoard在WM_CREATE消息处初始化为零):

void LabelsToBoard(void)
{
    int   iRow, iCol;
    TCHAR szTemp[2];

    for (iRow = 0; iRow < SIZE; iRow++)
        for (iCol = 0; iCol < SIZE; iCol++)
        {
            GetWindowText(hwndLabels[iRow][iCol], szTemp, 2);
            if (szTemp[0] != ' ')
                arrBoard[iRow][iCol] = szTemp[0] - '0';
        }
}
void BoardToLabels(void)
{
    int iRow, iCol;
    TCHAR szTemp[2];

    szTemp[1] = '\0';
    for (iRow = 0; iRow < SIZE; iRow++)
        for (iCol = 0; iCol < SIZE; iCol++)
        {
            szTemp[0] = arrBoard[iRow][iCol] + '0';
            SetWindowText(hwndLabels[iRow][iCol], szTemp);
        }

}

怎么了?为什么它不起作用?

0 个答案:

没有答案