数独暴力算法

时间:2014-11-13 12:47:04

标签: java recursion brute-force

我必须编写一个暴力算法,用预定的方法解决数独。 对于解决方法,我对精神障碍有点兴趣。作业说我们必须使用至少给定的方法,isPermutationisPermutationRowisPermutationColisPermutationBlock,{{1} },isPermutationMatrixisValid

我真的不知道何时在solve方法中返回值,因为它必须是递归的。

我会非常感谢任何帮助:)

solve

2 个答案:

答案 0 :(得分:1)

只是一些一般性建议:

我认为你迷路了,因为老实说,这段代码很乱。

所以,首先建议:清理该代码。只需将您的isPermutation(int[])方法与以下内容进行比较 - 哪一个更容易阅读?如果你甚至无法阅读,更不用说理解它,你无法弄清楚为什么你的代码不起作用。请注意,内联注释非常详细,但只是为变量使用有意义的名称有助于大量工作。

/**
 * Checks whether the array is a valid permutation of all natural numbers within its length.
 * 
 * @param lineToCheck
 *            a line in sudoku, regardless of direction
 * @return whether the line is valid
 */
public static boolean isPermutation(int[] lineToCheck) {
    // numbersPerLine - will usually be nine, could be anything
    int numbersPerLine = lineToCheck.length;

    // for every number that should exist in the line...
    for (int currentExpectedNumber = 1; currentExpectedNumber <= numbersPerLine; currentExpectedNumber++) {
        boolean foundCurrentNumber = false;

        // ...check whether it is anywhere in the line.
        for (int numberInLine : lineToCheck) {
            if (currentExpectedNumber == numberInLine) {
                // great, we found the number, so check the next one
                foundCurrentNumber = true;
                break;
            }
        }
        if (!foundCurrentNumber) {
            /*
             * if we got here, the expected number could not be found anywhere in the line, so the line is NOT a valid permutation
             */
            return false;
        }
    }
    // all numbers were found, so we do in fact have a valid permutation
    return true;
}

下一条建议: 弄清楚你正在尝试做什么。你可能知道有几个Sudoku solving algorithms。按照代码所采用的步骤排列您尝试实现的算法步骤。你应该能够完成整个过程并发现差异。研究那些。

答案 1 :(得分:1)

您的代码中存在许多问题。

首先,方法isPermutation是错误的:当你应该循环到 9 {{1时,你循环到<{1}} 2 }!方法应该是:

key.length

如Patrick J Abare II所述,结局应该是a.length

接下来,您尝试使用暴力,但从不回溯。这对方法public static boolean isPermutation(int[] a) { int[][] key = new int[2][a.length]; key[0] = a; for (int i = 0; i < a.length; i++) { key[1][i] = 0; } for (int i = 0; i < a.length; i++) { if (a[i] > 0) { key[1][a[i] - 1]++; } } boolean keycheck = false; for (int i = 0; i < a.length; i++) { if (key[1][i] > 1) { keycheck = true; break; } } if (keycheck == true) { return false; } else { return true; } } return ! keycheck;应该处理任何级别的不可接受的值,应该是:

solve

这样,程序返回:

teilsolve