有一个5*5的网格,其中恰好有一个格子是空的,其他格子各有一个字母。一共有4中指令:A,B,L,R,分别表示把空格上、下、左、右的相邻字母移到空格中。输入初始网格和指令序列(以数字0结束),输出指令执行完毕后的网格。如果有非法指令,应输出“This puzzle has no final configuration.”例如,左图中执行ARRBBL0后,效果如右图所示。
![]()
这题不难,用到二维数组的应用,通过判断输入的指令来进行操作。
package smail;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int a = 1;
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
char[][] c = { { '0', '0', '0', '0', '0' }, { '0', '0', '0', '0', '0' }, { '0', '0', '0', '0', '0' },
{ '0', '0', '0', '0', '0' }, { '0', '0', '0', '0', '0' } };
String s;
int x = 0, y = 0;
// main.input();
for (int i1 = 0; i1 < 5; i1++) {
s = in.nextLine();
if (s.charAt(0) == 'Z')
System.exit(0);
if (s.length() == 4) {
for (int j = 0; j < 4; j++) {
c[i1][j] = s.charAt(j);
}
c[i1][4] = ' ';
x = i1;
y = 4;
} else
for (int j = 0; j < 5; j++) {
c[i1][j] = s.charAt(j);
if (c[i1][j] == ' ') {
x = i1;
y = j;
}
}
}
int a2 = 1;
boolean fa = true;
while (a2 == 1) {
String strl = in.nextLine();
// main.operation(strl);
char cc = 0;
if (strl.charAt(strl.length()-1) == '0') {
a2 = 0;
}
for (int i1 = 0; i1 < strl.length(); i1++) {
if (strl.charAt(i1) == 'A') {
if (x - 1 < 0) {
fa = false;
a2 = 0;
break;
} else {
cc = c[x - 1][y];
c[x - 1][y] = ' ';
c[x][y] = cc;
x = x - 1;
}
} else if (strl.charAt(i1) == 'B') {
if (x + 1 > 4) {
fa = false;
a2 = 0;
break;
} else {
cc = c[x + 1][y];
c[x + 1][y] = ' ';
c[x][y] = cc;
x = x + 1;
}
} else if (strl.charAt(i1) == 'L') {
if (y - 1 < 0) {
fa = false;
a2 = 0;
break;
} else {
cc = c[x][y - 1];
c[x][y - 1] = ' ';
c[x][y] = cc;
y = y - 1;
}
} else if (strl.charAt(i1) == 'R') {
if (y + 1 > 4) {
fa = false;
a2 = 0;
break;
} else {
cc = c[x][y + 1];
c[x][y + 1] = ' ';
c[x][y] = cc;
y = y + 1;
}
}
}
}
if (fa) {
if (a > 1)
System.out.println();
System.out.println("Puzzle" + " #" + a + ":");
// main.output();
for (int i1 = 0; i1 < 5; i1++) {
for (int j = 0; j < 5; j++) {
if (j == 4)
System.out.print(c[i1][j]);
else
System.out.print(c[i1][j] + " ");
}
System.out.println();
}
}
// TODO 自动生成的 catch 块
else {
System.out.println();
System.out.println("Puzzle #" + a + ":");
System.out.println("This puzzle has no final configuration.");
}
a++;
}
}
}