所以我对 Java 比较陌生(我目前正在我的学校学习 AP java),我正在尝试开发一种递归算法来解决 n*n 板,我觉得我非常接近,但还没有完全达到。我已经写了所有东西来遍历我的字典以查找我发送的字母是否是单词等。我的算法是让我的数组中的起始字母为 (n,p),将这些坐标发送到另一个方法去各个方向寻找所有可能的组合。一旦找到以 (n,p) 开头的所有组合,我将递增 p 直到它到达行的末尾,然后我将递增 n 并再次从 0 开始 p。(我只浏览了一半的字母,因为前后组合都是一样的)
我遇到问题的部分是递归序列,因为一旦我越过板上的某个位置,我想标记它以确保在序列的其余部分我永远不会再越过它。它不能完全工作,我想知道是否有人可以告诉我为什么/帮助我编写更好的算法。提前致谢
public void AllLetters(int n, int p, int x, int y,String word, String MyLetteres[][]){
int temp=0;
int StartLetter =(int)(Math.pow(MyLetteres.length,2));
while(temp<StartLetter)//runs through every letter
{
if(temp==0)
getPaths(p, n,x,y,word, MyLetteres);
else if(temp%(MyLetteres.length-1)==temp){
getPaths(p, n+1,x,y,word, MyLetteres);
}
else {
getPaths(p+1, 0,x,y,word, MyLetteres);
}
if(temp==(StartLetter/2-1)){
temp=StartLetter;
}
temp++;
}
}
public void getPaths(int p, int n, int x, int y,String word, String MyLetteres[][]){
if( x ==p-1 && y == n-1){//reach the (n,p) point
System.out.print("");
}else if( x >= MyLetteres.length || y >= MyLetteres.length||x < 0 || y < 0){//out of bounds
return;
}else {
if(x+1<MyLetteres.length&&!MyLetteres[x+1][y].equals("0")){//up{
word=word+""+MyLetteres[x+1][y];
Check(word);//function that checks if it is a word
reverse(word);//checks its a word backwards (for efficenicy)
MyLetteres[x+1][y]="0";//marking that I've used this position
System.out.print("1");//debugging purposes
getPaths(n,p, x +1, y,word , MyLetteres);
}
if(x-1>0&&!MyLetteres[x-1][y].equals("0")){//down
word=word+""+MyLetteres[x-1][y];
Check(word);
reverse(word);
MyLetteres[x-1][y]="0";
System.out.print("2");
getPaths(n,p, x -1, y ,word, MyLetteres);
}
if(y+1<MyLetteres.length&&!MyLetteres[x][y+1].equals("0")){//right
word=word+""+MyLetteres[x][y+1];
Check(word);
reverse(word);
MyLetteres[x][y+1]="0";
System.out.print("3");
getPaths(n, p,x , y +1,word, MyLetteres);
}
if(y-1>0&&!MyLetteres[x][y-1].equals("0")){//left
word=word+""+MyLetteres[x][y-1];
Check(word);
reverse(word);
MyLetteres[x][y-1]="0";
System.out.print("4");
getPaths(n,p, x , y -1,word, MyLetteres);
}
if(x+1<MyLetteres.length&&y+1<MyLetteres.length&&!MyLetteres[x+1][y+1].equals("0")){//right, up
word=word+""+MyLetteres[x+1][y+1];
Check(word);
reverse(word);
MyLetteres[x+1][y+1]="0";
System.out.print("5");
getPaths(n,p, x +1, y +1,word, MyLetteres);
}
if(x-1>0&&y-1>0&&!MyLetteres[x-1][y-1].equals("0")){//down, left
word=word+""+MyLetteres[x-1][y-1];
Check(word);
reverse(word);
MyLetteres[x-1][y-1]="0";
System.out.print("6");
getPaths(n,p, x-1 , y -1,word, MyLetteres);
}
if(x-1>0&&y+1<MyLetteres.length&&!MyLetteres[x-1][y+1].equals("0")){//down, right
word=word+""+MyLetteres[x-1][y+1];
Check(word);
reverse(word);
MyLetteres[x-1][y+1]="0";
System.out.print("7");
getPaths(n,p, x+1, y-1, word,MyLetteres);
}
if(x+1<MyLetteres.length&&y-1>0&&!MyLetteres[x+1][y-1].equals("0")){//up, left
word=word+""+MyLetteres[x+1][y-1];
Check(word);
reverse(word);
MyLetteres[x+1][y-1]="0";
System.out.print("8");
getPaths(n, p,x-1 , y +1, word,MyLetteres);
}
}
}