#include <bits/stdc++.h>
using namespace std;
struct node{
	string str;
	int count;
};
queue<node> q;

void swap(char &a, char &b)
{
	char temp = a;
	a = b;
	b = temp;
}

bool check(string s){
    if(s.find("2012") != string ::npos) return true;
    else return false;
}

void bfs(string &n, int s)
{
	node cur, temp;
	while (!q.empty()) 
	{
		cur = q.front();
		q.pop();
		if (check(cur.str)) 
		{
			cout << cur.count;
			return ;
		}
		else
		{
			for (int i=0; i<s-1; i++)
			{
				swap(cur.str[i], cur.str[i+1]);
				temp.str = cur.str;
				temp.count = cur.count+1;
				q.push(temp); 
				swap(cur.str[i], cur.str[i+1]);
			}
		}
	}
	cout<<-1<<endl;
}

int main()
{
	int n;
	string string;
	cin>>n>>string;
	node obj;
	obj.str = string;
	obj.count= 0;
	q.push(obj);
	bfs(string, n);
}

bfs模板题