rt.
#include<bits/stdc++.h>
#include<string>
using namespace std;
int as,n;
bool vis[100005];
struct point{
int val,step;
};
queue<point>Q;
//stoi:string->int;
//to_string:int->string
string to_string(int n)
{
string s="";
while(n)
{
s=char(n%10+'0')+s;
n/=10;
}
return s;
}
int stoi(string s)
{
int n=0;
for(int i=0;i<s.size();i++)
n=n*10+s[i]-'0';
return n;
}
void bfs()
{
vis[n]=1;
Q.push({n,0});
while(!Q.empty())
{
point now=Q.front();Q.pop();
if(now.val==as){cout<<now.step<<endl;return;}
string s=to_string(now.val);
int l=s.size();
string str;
for(int i=0;i<l;i++)
{
str=s;str.erase(i,1);
if(vis[stoi(str)]) continue;
vis[stoi(str)]=1,Q.push({stoi(str),now.step+1});
}
for(int i=0;i<l-1;i++)
for(int j=i+1;j<l;j++)
{
str=s;swap(str[i],str[j]);
if(vis[stoi(str)]) continue;
vis[stoi(str)]=1,Q.push({stoi(str),now.step+1});
}
for(int i=0;i<l-1;i++)
{
for(int j=str[i];j<=str[i+1];j++)
{
str=s;str.insert(str.begin()+i,j);
if(vis[stoi(str)]) continue;
vis[stoi(str)]=1,Q.push({stoi(str),now.step+1});
}
}
}
puts("-1");
}
void Solve()
{
cin>>n;
bfs();
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
int T;cin>>as>>T;
while(T--) Solve();
return 0;
}