Problem: Example

Input

0 3 1 7 5 9 8 6 4 2
7 0 9 2 1 5 4 8 6 3
4 2 0 6 8 7 1 3 5 9
1 7 5 0 9 8 3 4 2 6
6 1 2 3 0 4 5 9 7 8
3 6 7 4 2 0 9 5 8 1
5 8 6 9 7 2 0 1 3 4
8 9 4 5 3 6 2 0 1 7
9 4 3 8 6 1 7 2 0 5
2 5 8 1 4 3 6 7 9 0


Output

0

Solution (in CPP):

Solution:
#include <bits/stdc++.h>
using namespace std;

int x[10][10];
map<string,int> m;

int last(string s){
    int now=0;
    for (int i=0;i<4;++i)
        now=x[now][s[i]-'0'];
    return now;
}

int check(string s){
    int now=0;
    for (int i=0;i<5;++i)
        now=x[now][s[i]-'0'];
    return now;
}

int main(){
    cin.tie(0);
    ios::sync_with_stdio(false);
    for (int i=0;i<10;++i)
        for (int j=0;j<10;++j)
            cin >> x[i][j];
    string pre="",now,alt;
    for (int i=99999;i>=0;--i){
        if (i==9999) pre+='0';
        if (i==999) pre+='0';
        if (i==99) pre+='0';
        if (i==9) pre+='0';
        now=pre+to_string(i);
        m[now]=check(now);
    }
    int ans=0,ok;
    pre="";
    for (int i=9999;i>=0;--i){
        if (i==999) pre+='0';
        if (i==99) pre+='0';
        if (i==9) pre+='0';
        now=pre+to_string(i);
        now+='0'+last(now);
        ok=0;
        for (int i=0;i<5;++i){
            for (int j=0;j<10;++j){
                alt=now;
                alt[i]='0'+j;
                if (now!=alt&&m[alt]==0) ok=1;
            }
        }
        for (int i=0;i<4;++i){
            if (now[i]==now[i+1]) continue;
            swap(now[i],now[i+1]);
            if (m[now]==0) ok=1;
            swap(now[i],now[i+1]);
        }
        ans+=ok;
    }
    cout << ans << '\n';
}