我正在用java编程一个DFS问题,该问题是关于n谜题的。我有以下代码:
public class Dfssolution
{
public static int cost=0;
public static String goal;
public static int n=3;
public static HashSet<String> closedlist= new HashSet<String>();
public static boolean solved = false;
public static String current;
public static int spc;
public static String temp;
public static LinkedHashSet<String> openlist = new LinkedHashSet<String>();
public Dfssolution()
{
}
public static void main(String args []){
String start= "103256789";
goal = "130256789";
String temp;
openlist.add(start);
while (openlist.isEmpty() == false && solved == false){
current= openlist.iterator().next();
openlist.remove(current);
cost++;
if(current.equals(goal)){
System.out.println(cost);
solved=true;
break;
}
else{
closedlist.add(current);
if(checkRight(current)==true && openlist.contains(current) == false && closedlist.contains(current) == false){
temp= right(current);
openlist.add(temp);
}
if(checkUp(current)==true && openlist.contains(current) == false && closedlist.contains(current) == false){
temp= up(current);
openlist.add(temp);
}
if(checkDown(current)==true && openlist.contains(current) == false && closedlist.contains(current) == false){
temp= down(current);
openlist.add(temp);
}
if(checkLeft(current)==true && openlist.contains(current) == false && closedlist.contains(current) == false){
temp= left(current);
openlist.add(temp);
}
}
}
}
public static String left(String s){
String tem = s;
spc=tem.indexOf("0");
char [] x = tem.toCharArray();
char a = x[spc];
x[spc] = x[spc-1];
x[spc-1] = a;
tem= new String(x);
return tem;
}
public static String right(String s){
String tem = s;
spc=tem.indexOf("0");
char [] x = tem.toCharArray();
char a = x[spc];
x[spc] = x[spc+1];
x[spc+1] = a;
tem= new String(x);
return tem;
}
public static String up(String s){
String tem = s;
spc=tem.indexOf("0");
char [] x = tem.toCharArray();
char a = x[spc];
x[spc] = x[spc-n];
x[spc-n] = a;
tem= new String(x);
return tem;
}
public static String down(String s){
String tem = s;
spc=tem.indexOf("0");
char [] x = tem.toCharArray();
char a = x[spc];
x[spc] = x[spc+n];
x[spc+n] = a;
tem= new String(x);
return tem;
}
public static boolean checkUp(String s){
spc=s.indexOf("0");
if(spc > n-1){
return true;
}
else{
return false;
}
}
public static boolean checkDown(String s){
spc=s.indexOf("0");
if(spc < n*(n-1)){
return true;
}
else{
return false;
}
}
public static boolean checkLeft(String s){
spc=s.indexOf("0");
if(spc !=0 &&(spc % n) !=0){
return true;
}
else{
return false;
}
}
public static boolean checkRight(String s){
spc=s.indexOf("0");
if(spc !=n-1 && spc % n !=n-1){
return true;
}
else{
return false;
}
}
}
我正在测试它,看看它是否会返回扩展的节点数量(称为"成本"),以达到代码中的目标状态。我在一个简单的问题上测试了它,这个问题就是
103
256
789
作为start
状态和
130
256
789
作为goal
状态程序不打印cost
(扩展的节点数),该值应为2。
注意,n
表示3x3难题中的3
您需要将语句closedlist.add(current);
移动到else块的末尾。否则,每个条件都会检查closedlist
是否包含current
(确实包含,您只需将其放在此处),并且不会在openlist
中放入任何内容。
在这个更改之后,解决方案分两步找到,但还有另一个错误需要处理——您正在全局计算cost
,而如果您想找到最少的移动量,则应该为每个分支单独计算。