0

私は数独ソルバーに取り組んでいますが、解決方法でエラーが発生し、一時的に「解決」して試行とキャッチの例外を発生させました。

ただ、一網打尽なのが少し気になりArrayIndexOutOfBoundsExceptionます。try/catch 例外でエラーを隠すのではなく、エラーを修正したいだけです。

これは、try/catch がどのように見えるかです:

    try {
        if (puzzle.getNum(i, j) != puzzle.blank)
            return solve(nexti, nextj);
    } catch (ArrayIndexOutOfBoundsException e) {
        return true;
    }

行を変更するときに情報を取得したx > 8ので、 につながると考えていy++ます。そして のときy > 8、81 (9x9) 個のセルがすべて埋められているので、プログラムを実行する必要があります。

私はtry / catchメソッドを単純なものに変更する行について考えています

if((i > 8) && (j > 8)){
        return true;
}   

しかし、それは私にもたくさんのエラーを与えます。

修正は非常に単純ですが、概念的には重要であると確信しています。

4

2 に答える 2

1

I would add this check at the beginning of the method:

if( i >= puzzle.puzzleSize || j >= puzzle.puzzleSize )
{
    return false;
}

If you're out of bounds of the puzzle board in either direction, you clearly haven't found a solution, thus you return false. Your computation of nexti and nextj can be after this check because the next recursive call would handle the case when they become out of bounds.

You might be tempted to say "well, my nextj calcuation uses modulus, so it will never be out of bounds." That's true, but you also can't guarantee the method will be called with the right parameters, so it's worth checking.

于 2013-03-20T15:20:49.050 に答える
0

再帰メソッドを使用しているため、コードの最初の行に「終了条件」が必要です。

追加する

if((i > 8) && (j > 8)){
      return true;
}

メソッドの最初にトリックを実行する必要があります(j<8のときにi= 9を送信しないことが確実な場合)。これを行うときに発生した他のエラーは何ですか?

于 2013-03-20T15:02:39.190 に答える