using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Rextester
{
    public class Program
    {
        static void f(int i,int j,int[,]m,ref int[]k,int n)
        {
            if(j==n)
            {i++;j=0;}
            if(i<n)
            if(k[m[i,j]-1]==0){
               k[m[i,j]-1]=1;
                j++;
                while(j<n&&m[i,j]==m[i,j-1])j++;
                
                f(i,j,m,ref k,n);
            }
            else if(i==0)k[m[i,j]-1]++;
            else
            {
                if(k[m[i,j]-1]==1){
                    if(m[i-1,j]!=m[i,j]){k[m[i,j]-1]++;}
                    else
                    {if(j>0&&m[i,j-1]!=m[i,j]&&m[i-1,j-1]==m[i,j]){k[m[i,j]-1]++;}
                     if(j<n-1&&m[i,j+1]!=m[i,j]&&m[i-1,j+1]==m[i,j]){k[m[i,j]-1]++;}
                    }
                    
                }
                f(i,j+1,m,ref k,n);
            }
        }
        public static void Main(string[] args)
        {
            string[]s=Console.ReadLine().Split();
            int n=int.Parse(s[0]),k=int.Parse(s[1]);
            int[,]m=new int[n,n];
            int[]b=new int[k];
            for(int i=0;i<n;i++)
            {
                string[]r=Console.ReadLine().Split();
                for(int j=0;j<n;j++)m[i,j]=int.Parse(r[j]);
            }
            f(0,0,m,ref b,n);
            int br=0;
            for(int i=0;i<k;i++)
                if(b[i]==1)br++;
                Console.WriteLine(br);
        }
    }
}