第一行输入N,第二行输入N个数字,只包含0,1,2
输出字符串要移几位才能解开密码,如果无论移位多少次都解不开密码,输出-1
5 02120 5 02120
1 1
import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ //移位 int n=sc.nextInt(); String code=sc.next(); int moveTime=getMoveTime(code); System.out.println(moveTime); } } private static int getMoveTime(String code) { if(code.length()<4)return -1; List<String>record=new ArrayList<>();//记录已经交换过的结果,剪枝。 Queue<Help>queue=new LinkedList<>(); Help help=new Help(code,0); queue.offer(help); record.add(code); while(!queue.isEmpty()) { help=queue.poll(); if(help.s.contains("2012")) return help.cnt; for(int i=0;i<code.length()-1;i++) { char[]arr=help.s.toCharArray(); char temp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = temp; String after=new String(arr); if(!record.contains(after)) { record.add(after); queue.offer(new Help(after,help.cnt+1)); } } } return -1; } } class Help{ String s; int cnt; Help(String s,int cnt){ this.s=s; this.cnt=cnt;//交换次数 }