思路:
BFS求最短路径, 把每一个状态看成一个节点
只要已经到达过这个节点, 后续再访问的节点要么字典序比其大, 要么路径比其长
使用一个dist来记录当前状态的路径长度
使用一个pre来记录当前状态的前置状态, 且该前置状态的操作
import java.util.*;
class Main{
static Map<String, Integer> dist = new HashMap();
//String[0]: 上一状态, String[1]: 操作
static Map<String, String[]> pre = new HashMap();
public static void bfs(String begin, String end){
dist.put(begin, 0);
if(begin.equals(end)) return;
Queue<String> q = new LinkedList();
q.offer(begin);
while (!q.isEmpty()){
String poll = q.poll();
String m0 = move0(poll);
if(!dist.containsKey(m0)){
dist.put(m0, dist.get(poll) + 1);
q.offer(m0);
}
pre.putIfAbsent(m0, new String[]{poll, "A"});
String m1 = move1(poll);
if(!dist.containsKey(m1)){
dist.put(m1, dist.get(poll) + 1);
q.offer(m1);
}
pre.putIfAbsent(m1, new String[]{poll, "B"});
String m2 = move2(poll);
if(!dist.containsKey(m2)){
dist.put(m2, dist.get(poll) + 1);
q.offer(m2);
}
pre.putIfAbsent(m2, new String[]{poll, "C"});
if(m0.equals(end) || m1.equals(end) || m2.equals(end)) return;
}
}
public static String move0(String s){
int[][] ints = stringToint(s);
int[] t = ints[0];
ints[0] = ints[1];
ints[1] = t;
return intToString(ints);
}
public static String move1(String s){
int[][] ints = stringToint(s);
int[] t = new int[]{ints[0][3], ints[1][3]};
for(int i = 2; i >= 0; i--){
ints[0][i + 1] = ints[0][i];
ints[1][i + 1] = ints[1][i];
}
ints[0][0] = t[0];
ints[1][0] = t[1];
return intToString(ints);
}
public static String move2(String s){
int[][] ints = stringToint(s);
// 01 11 12 02
int t1 = ints[0][1];
ints[0][1] = ints[1][1];
ints[1][1] = ints[1][2];
ints[1][2] = ints[0][2];
ints[0][2] = t1;
return intToString(ints);
}
public static String intToString(int[][] ints){
StringBuilder sb = new StringBuilder();
for(int i = 0; i < 4; i++) sb.append(ints[0][i]);
for(int i = 3; i >= 0; i--) sb.append(ints[1][i]);
return sb.toString();
}
public static int[][] stringToint(String s){
if(s.length() < 8) return new int[][]{{}};
int[][] res = new int[2][4];
int idx = 0;
for(int i = 0; i < 4; i++) res[0][i] = s.charAt(idx++) - '0';
for(int i = 3; i >= 0; i--) res[1][i] = s.charAt(idx++) - '0';
return res;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String begin = "12345678";
String end = sc.nextLine().replaceAll(" ", "");
bfs(begin, end);
System.out.println(dist.get(end));
StringBuilder sb = new StringBuilder();
String cur = end;
while(cur != begin){
String[] strings = pre.get(cur);
cur = strings[0];
sb.append(strings[1]);
}
System.out.println(sb.reverse().toString());
}
}