有一个5*5的网格,其中恰好有一个格子是空的,其他格子各有一个字母。一共有4中指令:A,B,L,R,分别表示把空格上、下、左、右的相邻字母移到空格中。输入初始网格和指令序列(以数字0结束),输出指令执行完毕后的网格。如果有非法指令,应输出“This puzzle has no final configuration.”例如,左图中执行ARRBBL0后,效果如右图所示。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while(input.hasNext()){
int a=1;
char[][] gz = new char[5][5];//定义二位数组做一个5*5的格子
String strl;//用来存放A,B,L,R字符串;
char ans =0;//用来判定移动的格子
String s;//对输入的char型进行数据转换
int x=0,y=0;//用来标记空格的位置
for(int i=0;i<5;i++){
s=input.nextLine();
if(s.length()==5){
for(int j=0;j<5;j++){
gz[i][j]=s.charAt(j);
if(gz[i][j]==' '){//当输入空格时,用x,y记录空格的位置
x=i;
y=j;
}
}
}
}
int doing=1;
while(doing==1){
boolean judge=true;//定义一个变量来判断移动是否合法
strl=input.nextLine();
for(int i=0;i<strl.length();i++){
if(strl.charAt(i)=='0'){//若在输入控制移动字符串后输入0,则doing赋值为2,跳出循环
doing=2;
}
else if(strl.charAt(i)=='A'){//上移
if(x-1<0){
judge=false;
doing=2;
break;
}
else{
ans=gz[x-1][y];
gz[x-1][y]=' ';
gz[x][y]=ans;
x=x-1;
}
}
else if(strl.charAt(i)=='B'){//下移
if(x+1>5){
judge=false;
doing=2;
break;
}
else{
ans=gz[x+1][y];
gz[x+1][y]=' ';
gz[x][y]=ans;
x=x+1;
}
}
else if(strl.charAt(i)=='L'){//左移
if(y-1<0){
judge=false;
doing=2;
break;
}
else{
ans=gz[x][y-1];
gz[x][y-1]=' ';
gz[x][y]=ans;
y=y-1;
}
}
else if(strl.charAt(i)=='R'){//右移
if(y+1>5){
judge=false;
doing=2;
break;
}
else{
ans=gz[x][y+1];
gz[x][y+1]=' ';
gz[x][y]=ans;
y=y+1;
}
}
}
if(judge==true){
if(a>0){
System.out.println("Puzzle"+" "+"#"+a+":");
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (j == 4) {
System.out.print(gz[i][j]);
break;
}
System.out.print(gz[i][j] + " ");
}
System.out.println();
}
}
}
else{
System.out.println("Puzzle"+" "+"#"+a+":");
System.out.println("This puzzle has no final configuration.");
}
a++;
}
}
}
}