Problem:
Identically Colored Panels Connection    Dr. Fukuoka has invented fancy panels.

Each panel has a square shape of a unit size and 
has one of the six colors, namely, yellow, pink, red, purple, green and blue.

The panel has two remarkable properties.

One property is that, when two or more panels with the same color
are placed adjacently, their touching edges melt a little
and they are fused each other.
The fused panels are united into a polygonally shaped panel.


The other property is that the color of a panel can be changed 
to one of six colors by giving an electrical shock.
The resulting color can be controlled by its waveform.
The electrical shock to an already united panel changes
the color of the whole to a specified single color.  Since he wants to investigate the strength with respect to the
color and the size of a united panel compared to unit panels,
he tries to unite panels into a polygonal panel with a specified color.       Figure C-1: panels and their initial colors     Since many panels are simultaneously synthesized and generated on a base plate 
through some complex chemical processes,
the fabricated panels are randomly colored and
they are arranged in a rectangular shape on the base plate  (Figure C-1).

Note that the two purple (color 4) panels in Figure C-1 are
already united at the initial state since they are 
adjacent to each other.  Installing  electrodes to a panel, and
changing its color several times by giving electrical shocks
according to an appropriate sequence for a specified target color,
he can make a united panel merge the adjacent panels 
to unite them step by step
and can obtain a larger panel with the target color.

Unfortunately, panels will be broken when
they are struck by the sixth electrical shock.

That is, he can change the color of a panel or a united panel only 
five times.    Let us consider a case
where the panel at the upper left corner of the panel configuration
(Figure C-1) is attached with the electrodes.
First, changing the color of the panel from yellow to blue,
the two adjacent panels are fused into a united panel (Figure C-2).        Figure C-2: 
Change of the color of the panel at the upper left corner,
from yellow (color 1) to blue (color 6).      Second, changing the color of the upper left united panel from blue
to red, a united red panel that consists of three unit panels is newly formed
(Figure C-3).
Then, changing the color of the united panel from red to purple,
panels are united again to form a united panel of five unit panels
(Figure C-4).        Figure C-3: 
Change of the color of the panel at the upper left corner,
from blue (color 6) to red (color 3).          Figure C-4: 
Change of the color of the panel at the upper left corner,
from red (color 3) to purple (color 4).      Furthermore, through making a pink united panel in Figure C-5 by
changing the color from purple to pink, 
then, the green united panel in Figure C-6 is obtained
by changing the color from pink to green.
The green united panel consists of ten unit panels.        Figure C-5: 
Change of the color of the panel at the upper left corner, 
from  purple (color 4) to pink (color 2).          Figure C-6: 
Change of the color of the panel at the upper left corner,
from pink (color 2) to green (color 5).      In order to check the strength of united panels with 
various sizes and colors, he needs to unite as many panels
as possible with the target color.

Your job is to write a program that finds a sequence to change 
the colors five times 
in order to get the largest united panel with the target color.

Note that the electrodes are fixed to the panel at the upper left corner.   Input   The input consists of multiple datasets, each being in the following format.    h  w  c  p 1,1  p 1,2 ... p 1, w  p 2,1  p 2,2 ... p 2, w ...  p h ,1  p h ,2 ... p h , w    h and w are positive integers no more than 8 that
represent the height and the width of the given rectangle. c is a positive integer no more than 6 that represents
the target color of the finally united panel. p i , j is a positive integer no more than 6
that represents the initial color of the panel at the position
( i , j ). The end of the input is indicated by a line that consists of 
three zeros separated by single spaces.   Output   For each dataset, output the largest possible number of unit panels
in the united panel at the upper left corner with the target color
after five times of color changes of the panel 
at the upper left corner.
No extra characters should occur in the output.   Sample Input  3 5 5
1 6 3 2 5
2 5 4 6 1
1 2 4 1 5
4 5 6
1 5 6 1 2
1 4 6 3 2
1 5 2 3 2
1 1 2 3 2
1 1 5
1
1 8 6
1 2 3 4 5 1 2 3
8 1 1
1
2
3
4
5
1
2
3
8 8 6
5 2 5 2 6 5 4 2
4 2 2 2 5 2 2 2
4 4 4 2 5 2 2 2
6 4 5 2 2 2 6 6
6 6 5 5 2 2 6 6
6 2 5 4 2 2 6 6
2 4 4 4 6 2 2 6
2 2 2 5 5 2 2 2
8 8 2
3 3 5 4 1 6 2 3
2 3 6 4 3 6 2 2
4 1 6 6 6 4 4 4
2 5 3 6 3 6 3 5
3 1 3 4 1 5 6 3
1 6 6 3 5 1 5 3
2 4 2 2 2 6 5 3
4 1 3 6 1 5 5 4
0 0 0  Output for the Sample Input  10
18
1
5
6
64
33

Solution (Python):

from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S(): return list(sys.stdin.readline())[:-1]
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007


"""
n = int(input())
k = list("mcxi")
for i in range(n):
    d = {"m":0,"c":0,"x":0,"i":0}
    a,b  = input().split()
    a = list(a)
    b = list(b)
    a.insert(0,1)
    b.insert(0,1)
    for j in range(1,len(a)):
        if a[j] in k:
            if a[j-1] in k:
                d[a[j]] += 1
            else:
                d[a[j]] += int(a[j-1])
    for j in range(1,len(b))[::-1]:
        if b[j] in k:
            if b[j-1] in k:
                d[b[j]] += 1
            else:
                d[b[j]] += int(b[j-1])
            if d[b[j]] >= 10:
                l = b[j]
                while d[l] >= 10:
                    d[l] -= 10
                    l = k[k.index(l)-1]
                    d[l] += 1
    for j in k:
        if d[j]:
            if d[j] == 1:
                print(j,end = "")
            else:
                print(str(d[j])+j,end = "")
    print()
"""


"""
while 1:
    h, w = map(int, input().split())
    if h == w == 0:
        break
    s = [list(map(int, input().split())) for i in range(h)]

    ans = 0
    for u in range(h):
        for d in range(u+2,h):
            for l in range(w):
                for r in range(l+2,w):
                    m = float("inf")
                    for i in range(u,d+1):
                        m = min(m,s[i][l],s[i][r])
                    for i in range(l,r+1):
                        m = min(m,s[u][i],s[d][i])
                    f = 1
                    su = 0
                    for i in range(u+1,d):
                        for j in range(l+1,r):
                            su += (m-s[i][j])
                            if s[i][j] >= m:
                                f = 0
                                break
                        if not f:
                            break
                    if f:
                        ans = max(ans,su)
    print(ans)
"""


"""
while 1:
    m,n = map(int, input().split())
    if m == n == 0:
        break
    ma = 7368791
    d = [0]*(ma+1)
    z = m
    for i in range(n):
        while d[z]:
            z += 1
        j = z
        while j <= ma:
            d[j] = 1
            j += z
    for j in range(z,ma+1):
        if not d[j]:
            print(j)
            break
"""


"""
def factorize(n):
    if n < 4:
        return [1,n]
    i = 2
    l = [1]
    while i**2 <= n:
        if n%i == 0:
            l.append(i)
            if n//i != i:
                l.append(n//i)
        i += 1
    l.append(n)
    l.sort()
    return l
while 1:
    b = int(input())
    if b == 0:
        break
    f = factorize(2*b)
    for n in f[::-1]:
        a = 1-n+(2*b)//n
        if a >= 1 and a%2 == 0:
            print(a//2,n)
            break
"""


"""
import sys
dp = [100]*1000000
dp_2 = [100]*1000000
dp[0] = 0
dp_2[0] = 0
for i in range(1,181):
    s = i*(i+1)*(i+2)//6
    for j in range(s,1000000):
        if dp[j-s]+1 < dp[j]:
            dp[j] = dp[j-s]+1
    if s%2:
        for j in range(s,1000000):
            if dp_2[j-s]+1 < dp_2[j]:
                dp_2[j] = dp_2[j-s]+1
while 1:
    m = int(sys.stdin.readline())
    if m == 0:
        break
    print(dp[m],dp_2[m])
"""


"""
from collections import deque
while 1:
    n = int(input())
    if n == 0:
        break
    s = [input() for i in range(n)]
    d = [s[i].count(".") for i in range(n)]
    m = max(d)
    c = [s[i][-1] for i in range(n)]
    q = deque()
    for i in range(1,m+1)[::-1]:
        j = 0
        while j < n:
            for k in range(j,n):
                if d[k] == i:break
            else:
                break
            j = k
            op = c[j-1]
            while j < n and d[j] == i:
                q.append(j)
                j += 1
            j = k
            if op == "+":
                k = 0
                while q:
                    x = q.pop()
                    k += int(c[x])
                    c.pop(x)
                    d.pop(x)
                    n -= 1
            else:
                k = 1
                while q:
                    x = q.pop()
                    k *= int(c[x])
                    c.pop(x)
                    d.pop(x)
                    n -= 1
            c[j-1] = k
    print(c[0])
"""


"""
from collections import defaultdict

def parse_expr(s,i):
    i += 1
    if s[i] == "[":
        q = []
        while s[i] != "]":
            e,i = parse_expr(s,i)
            q.append(e)
        return (calc(q),i+1)
    else:
        n,i = parse_num(s,i)
        return (calc([n]),i+1)

def parse_num(s,i):
    m = int(s[i])
    i += 1
    while f_num[s[i]]:
        m *= 10
        m += int(s[i])
        i += 1
    return (m,i)

def calc(q):
    if len(q) == 1:
        return (q[0]+1)//2
    q.sort()
    return sum(q[:len(q)//2+1])

f_num = defaultdict(lambda : 0)
for i in range(10):
    f_num[str(i)] = 1

n = int(input())
for i in range(n):
    s = input()
    print(parse_expr(s,0)[0])
"""


"""
while 1:
    w,h = LI()
    if w == h == 0:
        break
    s = SR(h)
    dp = [[0]*w for i in range(h)]
    for y in range(h):
        for x in range(w):
            if s[y][x].isdecimal():
                dp[y][x] = max(dp[y-1][x],dp[y][x-1])*10+int(s[y][x])
    ans = 0
    for i in dp:
        ans = max(ans,max(i))
    print(ans)
"""

"""def parse_formula(s,i):
    if s[i] == "-":
        i += 1
        e,i = parse_formula(s,i)
        return 2-e,i
    elif s[i] == "(":
        i += 1
        e1,i = parse_formula(s,i)
        op = s[i]
        i += 1
        e2,i = parse_formula(s,i)
        i += 1
        return calc(op,e1,e2),i
    else:
        return int(s[i]),i+1

def calc(op,a,b):
    if op == "*":
        return min(a,b)
    else:
        return max(a,b)

while 1:
    s = S()
    if s[0] == ".":
        break
    t = []
    f = defaultdict(int)
    for p in range(3):
        f["P"] = p
        for q in range(3):
            f["Q"] = q
            for r in range(3):
                f["R"] = r
                t.append([f[s[i]] if s[i] in "PQR" else s[i] for i in range(len(s))])
    ans = 0
    for s in t:
        if parse_formula(s,0)[0] == 2:
            ans += 1
    print(ans)
"""

d = [(1,0),(-1,0),(0,1),(0,-1)]
def dfs(dep,s):
    global ans
    if dep == 5:
        b = bfs(s)
        m = 0
        for i in b:
            m += sum(i)
        ans = max(ans, m)
    else:
        if dep < 4:
            for i in range(6):
                b = bfs(s)
                dfs(dep+1,[[i+1 if b[y][x] else s[y][x] for x in range(w)] for y in range(h)])
        else:
            b = bfs(s)
            dfs(dep+1,[[c if b[y][x] else s[y][x] for x in range(w)] for y in range(h)])

def bfs(s):
    b = [[0]*w for i in range(h)]
    b[0][0] = 1
    q = deque([(0,0)])
    while q:
        y,x = q.popleft()
        for dy,dx in d:
            y_ = y+dy
            x_ = x+dx
            if 0 <= y_ < h and 0 <= x_ < w:
                if not b[y_][x_] and s[y_][x_] == s[0][0]:
                    b[y_][x_] = 1
                    q.append((y_,x_))
    return b

while 1:
    h,w,c = LI()
    if h == 0:
        break
    s = LIR(h)
    ans = 0
    dfs(0,s)
    print(ans)