Title Description
 The Maya had a password that could be unlocked if there were four consecutive 2012 numbers in the string. Give a string of length N, (2 = < n < = 13) the string contains only three numbers: 0, 1 and 2. Ask how many times the string needs to be shifted to unlock the password, and only two adjacent numbers can be moved each time. For example, after one shift of 02120, 20120012200221002102 can be obtained. Among them, 20120 meets the requirements, so the output is 1. If the password cannot be unlocked no matter how many shifts are made, output - 1.
Enter a description:
The input contains multiple sets of test data, each set of test data consists of two lines.
The first line is an integer N, representing the length of the string (2 < = N < = 13).
The second line is a string consisting of 0, 1 and 2 with length of N.
Output Description:
For each group of test data, if the password can be solved, output the minimum number of shifts; otherwise output - 1.
Example 1
 input
 copy
5
02120
 output
 copy
1

Solution 1: backtracking
Wrong, only 90 percent

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
//13
//1122121122200
public class Main
{
    public static void main(String[] args)
    {
        BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
        try {
            String str;
            while((str=br.readLine())!=null) {
            	int len = Integer.parseInt(str);
            	String mode = br.readLine();
            	char[] ch = mode.toCharArray();
            	if(mode.indexOf("2012") != -1) System.out.println("0");
            	else if(!isVaild(mode)) System.out.println("-1"); 
            	else {
            		int[]res = {len*len};
            		backtrack(res, ch, len-1, 0);
            		System.out.println(res[0]);
            	}
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void backtrack(int[] res, char[] ch, int n, int count) {
    	if(new String(ch).indexOf("2012") != -1) {
    		if(count < res[0]) res[0] = count; 
    		return;
    	}
    	 for (int i = n; i > 0; i--) {
    	      // in the current permutation
    	      swap(ch, i, i-1);
    	      count++;
    	      // use next integers to complete the permutations
    	      backtrack(res, ch, i-1, count);
    	      // backtrack
    	      swap(ch, i, i-1);
    	      count--;
    	 }
    }
    public static void swap(char[] ch, int i, int j) {
    	char temp = ch[i];
    	ch[i] = ch[j];
    	ch[j] = temp;
    }
    public static boolean isVaild(String str) {//Only when the string contains 0, 1 and 2 can 2012 be generated by displacement
        boolean b0 = false;
        boolean b1 = false;
        boolean b2 = false;
        for(char c : str.toCharArray()) {
            if(c == '0') {
                b0 = true;
            }else if(c == '1') {
                b1 = true;
            }else if(c == '2') {
                b2 = true;
            }else {
                return false;
            }
        }
        return b0&&b1&&b2;
    }
}

Solution 2: bfs, from other people's point of view, super bull

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;


public class Main
{
	public static Queue<String> q = new LinkedList<>();
	public static Map<String, Integer> map = new HashMap<>();
    public static void main(String[] args)
    {
        BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
        try {
            String str;
            while((str=br.readLine())!=null) {
            	String mode = br.readLine();
            	char[] ch = mode.toCharArray();
            	if(mode.indexOf("2012") != -1) System.out.println("0");
            	else if(!isVaild(mode)) System.out.println("-1"); 
            	else System.out.println(BFS(mode));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static int BFS(String str) {
    	q.add(str);//The initial string is put into the queue as the starting point
    	map.put(str, 0);//The number of exchanges experienced by the initial string is 0
    	while(!q.isEmpty()) {
    		str = q.poll();//Take out the team leader and store it in str
    		for(int i = 0; i < str.length()-1; i++) {//Try an exchange
    			char[] ch = str.toCharArray();
    			swap(ch, i, i+1);//The new string is obtained by str swapping i bits and i+1 bits
    			String newStr = new String(ch);
    			if(!map.containsKey(newStr)){//If this string doesn't appear
    				map.put(newStr, map.get(str)+1);//Now it's there, and it's one more exchange than his father
    				if(newStr.indexOf("2012") != -1) return map.get(newStr);//Meet the requirements and stop work
    				else q.add(newStr);//Unqualified, continue bfs and put it in the queue
    			}
    			else continue;//The string that has appeared does not need to be processed
    		}
    	}
    	return -1;//Traversal completed, no strings found, return - 1
    }
    public static void swap(char[] ch, int i, int j) {
    	char temp = ch[i];
    	ch[i] = ch[j];
    	ch[j] = temp;
    }
    public static boolean isVaild(String str) {//Only when the string contains 0, 1 and 2 can 2012 be generated by displacement
        boolean b0 = false;
        boolean b1 = false;
        boolean b2 = false;
        for(char c : str.toCharArray()) {
            if(c == '0') {
                b0 = true;
            }else if(c == '1') {
                b1 = true;
            }else if(c == '2') {
                b2 = true;
            }else {
                return false;
            }
        }
        return b0&&b1&&b2;
    }
}
Dongshan a Qiang
175 original articles published, 20 praised, 8822 visited