チェス盤の周りを騎士にして、フルツアーを完了するか、どこに行かなくても騎士を動かすように指示します。Java:可能な移動が残らなくなるまでチェス盤で騎士を動かす方法
私はそれ以上の動きがなくなってから実際に停止する方法を見つけ出すのに問題があります。チェス盤の境界を確認するだけでなく、動きのアルゴリズムも持っています。プログラムは継続的に完璧なツアーが作成されていない場合は存在しないスポットを見つけようとしますので、
、うち64だけ倍にループ回数を設定します。私はこの問題を解決しなければならなかった
2アイデア変数をインクリメントするかであるたびに、特定の位置は、特定のスポットを中心にチェックし、すべての可能な移動が前の動きによって取られている場合、プログラムを終了しています。問題は、実際にこれをどうやって行うのか分かりません。
私が持っていたもう1つのアイデアは、2秒後にforループを終了することです(forループは各位置の方法を2回以上確認します)が、私の教授が私に逆らって逆さまにするような気がします私は次のコードで私の研究室を修正することができました
import apcslib.*; //this is only for Format()
public class ktour
{
int[][] kboard = new int[9][9];
int[] vert = new int[9];
int[] horiz = new int[9];
ktour()
{
vert[1] = -2;vert[2] = -1;vert[3] = 1;vert[4] = 2;vert[5] = 2;vert[6] = 1;vert[7] = -1;vert[8] = -2;
horiz[1] = 1;horiz[2] = 2;horiz[3] = 2;horiz[4] = 1;horiz[5] = -1;horiz[6] = -2;horiz[7] = -2;horiz[8] = -1;
path();
}
public void path()
{
int row = 1;
int col = 1;
int loops = 10; //i have this set to 10 for now
int col2 = 1;
int row2 = 1;
int r = (int)(Math.random() * (8) +1); //returns a random from 1 to 9
//System.out.println(r);
kboard[col][row] = 1;
for(int x = 2; x < loops; x++) //this runs the bounds check and places each number for the amount that loops is
{
r = (int)(Math.random() * (8) +1);
col = col2;
row = row2;
col = col + vert[r];
row = row + horiz[r];
while(col <= 0 || col > 8 || row <= 0 || row > 8) //bounds check, will keep running until both row and columb is in the board
{
r = (int)(Math.random() * (8) + 1);
col = col2;
row = row2;
col = col + vert[r];
row = row + horiz[r];
}
if(kboard[col][row] == 0)
{
kboard[col][row] = x;
row2 = row;
col2 = col;
}
else
{
x--; //if the above if is false and a number already occupies the generated spot, x is decremented and the program tries again
}
}
printboard();
}
public void printboard()
{
for(int y = 1; y < 9; y++)
{
System.out.println();
for(int x = 1; x < 9; x++)
{
System.out.print(Format.right(kboard[y][x],3));
}
}
}
}
いくつかのオプションがあります。たとえば、以下のようなアイデアがあります:あなたの境界チェックループでは、新しいランダム 'r'を選ぶのではなく、あなたがすでに持っている' r'に1を加えてください。もし9になったら、1から始めてください。 'r'があなたが始めた場所(別の変数に格納する必要がある場所)に戻ったら、可能なすべての動きを試しました。 –
@ OleV.V。問題は私の境界チェックで、その点が実際のチェッカーボードの内側であるかどうかをチェックするだけで、スポットが0の場合ではない –