list = new ArrayList();
list.add(new Move(x1,y1,0,start));//添加初始状态进入list
set.add(start);//添加初始字符串进入set
while(!list.isEmpty()){//当如果list不是空的,继续处理
Move now = list.get(0);//把list中第一个内容,赋给now,通过重复的获取list第一个内容进行判断,直至list为空结束,复杂度较大这样可能会导致超时
list.remove(0);//再把list中第一个移除
if(now.temp.equals(end)){//当前状态为最终状态时,直接退出
System.out.println(now.step);
return;
}
for(int i=0;i<4;i++){
int x=now.x+move[i][0];
int y=now.y+move[i][1];
if(x<0||x>2||y<0||y>2)//判断是否出现九宫格越界
continue;
int step=now.step+1;
char n=now.temp.charAt(x*3+y);//获取当前交换的新字符
String temp0 = now.temp;
temp0=temp0.replace(n, '-');//交换'.'字符和n字符
temp0=temp0.replace('.', n);
temp0=temp0.replace('-', '.');
if(!set.contains(temp0)){//判定当前行走结果是否已经行走过
set.add(temp0);//没有,将字符串temp0加入set,记录下来
list.add(new Move(x,y,step,temp0));//将当前'.'所在位置信息x,y,当前移动的次数step,以及当前字符串temp0添加到list列表中,while循环继续
}
}
}
System.out.println("-1");
return;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
九宫重排 test = new 九宫重排();
Scanner input = new Scanner(System.in);
start = input.next();//九宫格的初始状态
end = input.next();//九宫格的最终状态
test.bfs();
}
}