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):
import sys,copy,itertools as it
sys.setrecursionlimit(10000)

dxy = zip([1,0,-1,0],[0,1,0,-1])
def check(A):
    if A[0] == _P[0][0] or A[-1] != c: return False
    for i in xrange(1,len(A)):
        if A[i-1] == A[i]: return False
    return True
    
def rec(x,y,b,c):
    P[y][x] = c
    for dx,dy in dxy:
        nx,ny = x+dx,y+dy
        if 0 <= nx < w and 0 <= ny < h and P[ny][nx] == b:
            rec(nx,ny,b,c)
    
while 1:
    h,w,c = map(int,raw_input().split())
    if h == 0: break
    _P = [map(int,raw_input().split()) for i in xrange(h)]

    ans = 0
    for change in it.product(range(1,7),repeat = 5):
        if not check(change): continue
        P = copy.deepcopy(_P)
        for c in change: rec(0,0,P[0][0],c)
        rec(0,0,P[0][0],0)
        ans = max(ans, sum(p.count(0) for p in P))

    print ans

Solution (Python):
import copy
import itertools
import sys

if sys.version[0] == '2':
    range, input = xrange, raw_input


drc = [(-1, 0), (0, 1), (1, 0), (0, -1)]
C_NUM = 6
while True:
    H, W, C = map(int, input().split())
    if not (H | W | C):
        break
    board = [[int(x) - 1 for x in input().split()] for _ in range(H)]
    ans = 0
    for ope in itertools.product(range(C_NUM), repeat=4):
        
        tmp_board = copy.deepcopy(board)
        for color in itertools.chain(ope, (C - 1,)):
            now_c = tmp_board[0][0]
            if now_c == color:
                continue

            tmp_board[0][0] = color
            stack = [(0, 0)]
            while stack:
                r, c = stack.pop()
                for dr, dc in drc:
                    nr, nc = r + dr, c + dc
                    if 0 <= nr < H and 0 <= nc < W and tmp_board[nr][nc] == now_c:
                        tmp_board[nr][nc] = color
                        stack.append((nr, nc))
        tmp_board[0][0] = -1
        stack = [(0, 0)]
        while stack:
            r, c = stack.pop()
            for dr, dc in drc:
                nr, nc = r + dr, c + dc
                if 0 <= nr < H and 0 <= nc < W and tmp_board[nr][nc] == C - 1:
                    tmp_board[nr][nc] = -1
                    stack.append((nr, nc))
        ans = max(ans, sum(row.count(-1) for row in tmp_board))
    print(ans)

Solution (Python):
import copy
import itertools
import sys

if sys.version[0] == '2':
    range, input = xrange, raw_input

drc = [(-1, 0), (0, 1), (1, 0), (0, -1)]
C_NUM = 6


while True:
    H, W, C = map(int, input().split())
    if not (H | W | C):
        break
    board = [[int(x) - 1 for x in input().split()] for _ in range(H)]
    ans = 0
    for ope in itertools.product(range(C_NUM), repeat=4):
        
        ps = [(0, 0)]
        tmp_board = copy.deepcopy(board)
        for color in itertools.chain(ope, (C - 1,)):
            now_c = tmp_board[0][0]
            if now_c == color:
                continue

            for r, c in ps:
                tmp_board[r][c] = color
            stack = ps[:]
            while stack:
                r, c = stack.pop()
                for dr, dc in drc:
                    nr, nc = r + dr, c + dc
                    if 0 <= nr < H and 0 <= nc < W and tmp_board[nr][nc] == now_c:
                        tmp_board[nr][nc] = color
                        stack.append((nr, nc))
                        ps.append((nr, nc))
        for r, c in ps:
            tmp_board[r][c] = -1
        stack = ps[:]
        while stack:
            r, c = stack.pop()
            for dr, dc in drc:
                nr, nc = r + dr, c + dc
                if 0 <= nr < H and 0 <= nc < W and tmp_board[nr][nc] == C - 1:
                    tmp_board[nr][nc] = -1
                    stack.append((nr, nc))
        cand = sum(row.count(-1) for row in tmp_board)
        if cand > ans:
            ans = cand
    print(ans)

Solution (Python):
import copy
import itertools
import sys

if sys.version[0] == '2':
    range, input = xrange, raw_input

drc = [(-1, 0), (0, 1), (1, 0), (0, -1)]
C_NUM = 6


while True:
    H, W, C = map(int, input().split())
    if not (H | W | C):
        break
    board = [[int(x) - 1 for x in input().split()] for _ in range(H)]
    ans = 0
    for ope in itertools.product(range(C_NUM), repeat=5):
        
        if ope[0] == board[0][0] or ope[-1] != C - 1 or any(ope[i] == ope[i + 1] for i in range(4)):
            continue
        ps = [(0, 0)]
        tmp_board = copy.deepcopy(board)
        for color in ope:
            now_c = tmp_board[0][0]
            if now_c == color:
                continue

            for r, c in ps:
                tmp_board[r][c] = color
            stack = ps[:]
            while stack:
                r, c = stack.pop()
                for dr, dc in drc:
                    nr, nc = r + dr, c + dc
                    if 0 <= nr < H and 0 <= nc < W and tmp_board[nr][nc] == now_c:
                        tmp_board[nr][nc] = color
                        stack.append((nr, nc))
                        ps.append((nr, nc))
        for r, c in ps:
            tmp_board[r][c] = -1
        stack = ps[:]
        while stack:
            r, c = stack.pop()
            for dr, dc in drc:
                nr, nc = r + dr, c + dc
                if 0 <= nr < H and 0 <= nc < W and tmp_board[nr][nc] == C - 1:
                    tmp_board[nr][nc] = -1
                    stack.append((nr, nc))
        cand = sum(row.count(-1) for row in tmp_board)
        if cand > ans:
            ans = cand
    print(ans)

Solution (Python):
import copy
import itertools
import sys

if sys.version[0] == '2':
    range, input = xrange, raw_input

drc = [(-1, 0), (0, 1), (1, 0), (0, -1)]
C_NUM = 6


while True:
    H, W, C = map(int, input().split())
    if not (H | W | C):
        break
    board = [[int(x) - 1 for x in input().split()] for _ in range(H)]
    ans = 0
    for ope in itertools.product(range(C_NUM), repeat=5):
        
        if ope[0] == board[0][0] or ope[-1] != C - 1 or any(ope[i] == ope[i + 1] for i in range(4)):
            continue
        ps = [(0, 0)]
        tmp_board = copy.deepcopy(board)
        for color in ope:
            now_c = tmp_board[0][0]
            if now_c == color:
                continue

            for r, c in ps:
                tmp_board[r][c] = color
            stack = ps[:]
            while stack:
                r, c = stack.pop()
                for dr, dc in drc:
                    nr, nc = r + dr, c + dc
                    if 0 <= nr < H and 0 <= nc < W and tmp_board[nr][nc] == now_c:
                        tmp_board[nr][nc] = color
                        stack.append((nr, nc))
                        ps.append((nr, nc))
        for r, c in ps:
            tmp_board[r][c] = -1
        stack = ps[:]
        while stack:
            r, c = stack.pop()
            for dr, dc in drc:
                nr, nc = r + dr, c + dc
                if 0 <= nr < H and 0 <= nc < W and tmp_board[nr][nc] == C - 1:
                    tmp_board[nr][nc] = -1
                    stack.append((nr, nc))
        cand = sum(row.count(-1) for row in tmp_board)
        if cand > ans:
            ans = cand
    print(ans)

Solution (Python):
import copy
import itertools
import sys

if sys.version[0] == '2':
    range, input = xrange, raw_input

drc = [(-1, 0), (0, 1), (1, 0), (0, -1)]
C_NUM = 6

def dfs(r, c, now_c, next_c):
    tmp_board[r][c] = next_c
    for dr, dc in drc:
        nr, nc = r + dr, c + dc
        if 0 <= nr < H and 0 <= nc < W and tmp_board[nr][nc] == now_c:
            dfs(nr, nc, now_c, next_c)


while True:
    H, W, C = map(int, input().split())
    if not (H | W | C):
        break
    board = [[int(x) - 1 for x in input().split()] for _ in range(H)]
    ans = 0
    for ope in itertools.product(range(C_NUM), repeat=5):
        
        if ope[0] == board[0][0] or ope[-1] != C - 1 or any(ope[i] == ope[i + 1] for i in range(4)):
            continue
        tmp_board = copy.deepcopy(board)
        for color in ope:
            dfs(0, 0, tmp_board[0][0], color)
        dfs(0, 0, tmp_board[0][0], -1)
        cand = sum(row.count(-1) for row in tmp_board)
        if cand > ans:
            ans = cand
    print(ans)

Solution (Python):
import copy
import itertools
import sys

if sys.version[0] == '2':
    range, input = xrange, raw_input

drc = [(-1, 0), (0, 1), (1, 0), (0, -1)]
C_NUM = 6

def dfs(r, c, now_c, next_c):
    tmp_board[r][c] = next_c
    for dr, dc in drc:
        nr, nc = r + dr, c + dc
        if 0 <= nr < H and 0 <= nc < W and tmp_board[nr][nc] == now_c:
            dfs(nr, nc, now_c, next_c)


while True:
    H, W, C = map(int, input().split())
    if not (H | W | C):
        break
    board = [[int(x) - 1 for x in input().split()] for _ in range(H)]
    ans = 0
    for ope in itertools.product(range(C_NUM), repeat=5):
        
        if ope[0] == board[0][0] or ope[-1] != C - 1 or any(ope[i] == ope[i + 1] for i in range(4)):
            continue
        tmp_board = copy.deepcopy(board)
        for color in ope:
            dfs(0, 0, tmp_board[0][0], color)
        dfs(0, 0, tmp_board[0][0], -1)
        cand = sum(row.count(-1) for row in tmp_board)
        if cand > ans:
            ans = cand
    print(ans)

Solution (Python):
import copy
import itertools
import sys

if sys.version[0] == '2':
    range, input = xrange, raw_input

drc = [(-1, 0), (0, 1), (1, 0), (0, -1)]
C_NUM = 6

def dfs(r, c, now_c, next_c):
    tmp_board[r][c] = next_c
    for dr, dc in drc:
        nr, nc = r + dr, c + dc
        if 0 <= nr < H and 0 <= nc < W and tmp_board[nr][nc] == now_c:
            dfs(nr, nc, now_c, next_c)


while True:
    H, W, C = map(int, input().split())
    if not (H | W | C):
        break
    board = [[int(x) - 1 for x in input().split()] for _ in range(H)]
    ans = 0
    for ope in itertools.product(range(C_NUM), repeat=4):
        
        if ope[0] == board[0][0] or ope[-1] == C - 1 or any(ope[i] == ope[i + 1] for i in range(3)):
            continue
        tmp_board = copy.deepcopy(board)
        for color in itertools.chain(ope, (C - 1, )):
            dfs(0, 0, tmp_board[0][0], color)
        dfs(0, 0, tmp_board[0][0], -1)
        cand = sum(row.count(-1) for row in tmp_board)
        if cand > ans:
            ans = cand
    print(ans)

Solution (Python):
import copy
import itertools
import sys

if sys.version[0] == '2':
    range, input = xrange, raw_input

drc = [(-1, 0), (0, 1), (1, 0), (0, -1)]
C_NUM = 6

def dfs(r, c, now_c, next_c):
    tmp_board[r][c] = next_c
    for dr, dc in drc:
        nr, nc = r + dr, c + dc
        if 0 <= nr < H and 0 <= nc < W and tmp_board[nr][nc] == now_c:
            dfs(nr, nc, now_c, next_c)


while True:
    H, W, C = map(int, input().split())
    if not (H | W | C):
        break
    board = [[int(x) - 1 for x in input().split()] for _ in range(H)]
    ans = 0
    for ope in itertools.product(range(C_NUM), repeat=4):
        
        if ope[0] == board[0][0] or ope[-1] == C - 1 or any(ope[i] == ope[i + 1] for i in range(3)):
            continue
        tmp_board = copy.deepcopy(board)
        for color in itertools.chain(ope, (C - 1, )):
            dfs(0, 0, tmp_board[0][0], color)
        dfs(0, 0, tmp_board[0][0], -1)
        cand = sum(row.count(-1) for row in tmp_board)
        if cand > ans:
            ans = cand
    print(ans)

Solution (Python):
import copy
import itertools
import sys

if sys.version[0] == '2':
    range, input = xrange, raw_input

drc = [(-1, 0), (0, 1), (1, 0), (0, -1)]
C_NUM = 6


def dfs(r, c, now_c, next_c):
    tmp_board[r][c] = next_c
    for dr, dc in drc:
        nr, nc = r + dr, c + dc
        if 0 <= nr < H and 0 <= nc < W and tmp_board[nr][nc] == now_c:
            dfs(nr, nc, now_c, next_c)


while True:
    H, W, C = map(int, input().split())
    if not (H | W | C):
        break
    board = [[int(x) - 1 for x in input().split()] for _ in range(H)]
    ans = 0
    for ope in itertools.product(range(C_NUM), repeat=4):
        if ope[0] == board[0][0] or ope[-1] == C - 1 or any(ope[i] == ope[i + 1] for i in range(3)):
            continue
        tmp_board = copy.deepcopy(board)
        for color in ope:
            dfs(0, 0, tmp_board[0][0], color)
        dfs(0, 0, tmp_board[0][0], C - 1)
        dfs(0, 0, tmp_board[0][0], -1)
        cand = sum(row.count(-1) for row in tmp_board)
        if cand > ans:
            ans = cand
    print(ans)

Solution (Python):
import copy
import itertools
import sys

if sys.version[0] == '2':
    range, input = xrange, raw_input

drc = [(-1, 0), (0, 1), (1, 0), (0, -1)]
C_NUM = 6


def dfs(r, c, now_c, next_c):
    tmp_board[r][c] = next_c
    for dr, dc in drc:
        nr, nc = r + dr, c + dc
        if 0 <= nr < H and 0 <= nc < W and tmp_board[nr][nc] == now_c:
            dfs(nr, nc, now_c, next_c)


while True:
    H, W, C = map(int, input().split())
    if not (H | W | C):
        break
    board = [[int(x) - 1 for x in input().split()] for _ in range(H)]
    ans = 0
    for ope in itertools.product(range(C_NUM), repeat=4):
        if ope[0] == board[0][0] or ope[-1] == C - 1 or any(ope[i] == ope[i + 1] for i in range(3)):
            continue
        tmp_board = copy.deepcopy(board)
        for color in ope:
            dfs(0, 0, tmp_board[0][0], color)
        dfs(0, 0, tmp_board[0][0], C - 1)
        dfs(0, 0, tmp_board[0][0], -1)
        cand = sum(row.count(-1) for row in tmp_board)
        if cand > ans:
            ans = cand
    print(ans)

Solution (Python):
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(0,-1),(1,0),(0,1),(-1,0)]
ddn = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,-1),(-1,0),(-1,1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)

def main():
    rr = []


    while True:
        h,w,c = LI()
        if h == 0:
            break
        a = [LI() for _ in range(h)]
        mc = max(map(max,a))
        d = collections.defaultdict(int)
        for i in range(h):
            for j in range(w):
                d[(i,j)] = a[i][j]

        def f(c,s):
            ff = True
            ts = s
            while ff:
                r = set()
                ff = False
                for i,j in ts:
                    for di,dj in dd:
                        ni = i + di
                        nj = j + dj
                        if d[(ni,nj)] == c and not (ni,nj) in ts:
                            ff = True
                            r.add((ni,nj))
                ts = ts | r
            return ts

        r = 0
        s = f(a[0][0], set([(0,0)]))
        for ca in itertools.product(range(1,mc+1), repeat=4):
            ts = s
            for nc in ca:
                ts = f(nc, ts)
            ts = f(c, ts)
            if r < len(ts):
                r = len(ts)
        rr.append(r)

    return '\n'.join(map(str, rr))



print(main())

Solution (Python):
direct = ((0, -1), (0, 1), (-1, 0), (1, 0))

def comb(color, mp, pos):
  end = len(pos)
  ind = 0
  while ind < end:
    x, y = pos[ind]
    for dx, dy in direct:
      nx, ny = x + dx, y + dy
      if (nx, ny) not in pos and mp[ny][nx] == color:
        pos.append((nx, ny))
        end += 1
    ind += 1

def search(rest, now_color, goal_color, pos, mp):
  if rest == 0:
    return len(pos)
  if rest == 1:
    if now_color != goal_color:
      next_pos = pos[:]
      comb(goal_color, mp, next_pos)
      return len(next_pos)
    else:
      return 0

  ret = 0
  for next_color in range(1, 7):
    if next_color != now_color:
      next_pos = pos[:]
      comb(next_color, mp, next_pos)
      ret = max(ret, search(rest - 1, next_color, goal_color, next_pos, mp))
  return ret

def main():
  while True:
    h, w, c = map(int, input().split())
    if h == 0:
      break
    mp = [[-1] + list(map(int, input().split())) + [-1] for _ in range(h)]
    mp.insert(0, [-1] * (w + 2))
    mp.append([-1] * (w + 2))
    init_pos = [(1, 1)]
    init_color = mp[1][1]
    comb(init_color, mp, init_pos)
    print(search(5, init_color, c, init_pos, mp))
main()

Solution (Python):
direct = ((0, -1), (0, 1), (-1, 0), (1, 0))

def comb(color, mp, pos):
  next_pos = pos[:]
  end = len(next_pos)
  ind = 0
  while ind < end:
    x, y = next_pos[ind]
    for dx, dy in direct:
      nx, ny = x + dx, y + dy
      if (nx, ny) not in next_pos and mp[ny][nx] == color:
        next_pos.append((nx, ny))
        end += 1
    ind += 1
  return next_pos

def search(rest, now_color, goal_color, pos, mp):
  if rest == 1:
    if now_color != goal_color:
      next_pos = comb(goal_color, mp, pos)
      return len(next_pos)
    return 0

  ret = 0
  for next_color in range(1, 7):
    if next_color != now_color:
      next_pos = comb(next_color, mp, pos)
      ret = max(ret, search(rest - 1, next_color, goal_color, next_pos, mp))
  return ret

def main():
  while True:
    h, w, c = map(int, input().split())
    if h == 0:
      break
    mp = [[-1] + list(map(int, input().split())) + [-1] for _ in range(h)]
    mp.insert(0, [-1] * (w + 2))
    mp.append([-1] * (w + 2))
    init_pos = [(1, 1)]
    init_color = mp[1][1]
    init_pos = comb(init_color, mp, init_pos)
    print(search(5, init_color, c, init_pos, mp))
main()

Solution (Python):
direct = ((0, -1), (0, 1), (-1, 0), (1, 0))

def comb(target_color, mp, pos):
  next_pos = pos[:]
  end = len(next_pos)
  ind = 0
  while ind < end:
    x, y = next_pos[ind]
    for dx, dy in direct:
      nx, ny = x + dx, y + dy
      if mp[ny][nx] == target_color and (nx, ny) not in next_pos:
        next_pos.append((nx, ny))
        end += 1
    ind += 1
  return next_pos

def search(rest, now_color, goal_color, pos, mp):
  if rest == 1:
    if now_color != goal_color:
      next_pos = comb(goal_color, mp, pos)
      return len(next_pos)
    return 0

  ret = 0
  for next_color in range(1, 7):
    if next_color != now_color:
      next_pos = comb(next_color, mp, pos)
      ret = max(ret, search(rest - 1, next_color, goal_color, next_pos, mp))
  return ret

def main():
  while True:
    h, w, c = map(int, input().split())
    if h == 0:
      break
    mp = [[-1] + list(map(int, input().split())) + [-1] for _ in range(h)]
    mp.insert(0, [-1] * (w + 2))
    mp.append([-1] * (w + 2))
    init_pos = [(1, 1)]
    init_color = mp[1][1]
    init_pos = comb(init_color, mp, init_pos)
    print(search(5, init_color, c, init_pos, mp))
main()

Solution (Python):
from collections import deque

p_copy = []


def change(y):
    global p_copy
    x = p_copy[0][0]
    que = deque()
    que.append((0, 0))
    memo = {(0, 0): 1}
    while len(que) > 0:
        i, j = que.popleft()
        p_copy[i][j] = y
        if i + 1 < h and p_copy[i + 1][j] == x and (i + 1, j) not in memo:
            que.append((i + 1, j))
            memo[(i + 1, j)] = 1
        if j + 1 < w and p_copy[i][j + 1] == x and (i, j + 1) not in memo:
            que.append((i, j + 1))
            memo[(i, j + 1)] = 1
        if i - 1 >= 0 and p_copy[i - 1][j] == x and (i - 1, j) not in memo:
            que.append((i - 1, j))
            memo[(i - 1, j)] = 1
        if j - 1 >= 0 and p_copy[i][j - 1] == x and (i, j - 1) not in memo:
            que.append((i, j - 1))
            memo[(i, j - 1)] = 1


def count():
    global p_copy
    res = 0
    que = deque()
    if p_copy[0][0] == c:
        que.append((0, 0))
    memo = {(0, 0): 1}
    while len(que) > 0:
        i, j = que.popleft()
        res += 1
        if i + 1 < h and p_copy[i + 1][j] == c and (i + 1, j) not in memo:
            que.append((i + 1, j))
            memo[(i + 1, j)] = 1
        if j + 1 < w and p_copy[i][j + 1] == c and (i, j + 1) not in memo:
            que.append((i, j + 1))
            memo[(i, j + 1)] = 1
        if i - 1 >= 0 and p_copy[i - 1][j] == c and (i - 1, j) not in memo:
            que.append((i - 1, j))
            memo[(i - 1, j)] = 1
        if j - 1 >= 0 and p_copy[i][j - 1] == c and (i, j - 1) not in memo:
            que.append((i, j - 1))
            memo[(i, j - 1)] = 1
    return res


_max = 0


def solve(p, n, before):
    global _max, p_copy
    if n == 1:
        change(c)
        temp = count()
        if temp > _max:
            _max = temp
        return
    for k in range(1, 7):
        if k == before:
            continue
        p_copy = [[j for j in i] for i in p]
        change(k)
        solve(p_copy, n - 1, k)


while True:
    h, w, c = map(int, input().split())
    if h | w | c == 0:
        break
    p_list = [list(map(int, input().split()))for i in range(h)]
    solve(p_list, 5, -1)
    print(_max)
    _max = 0

Solution (Python):
from collections import defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue,copy,time
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inp(): return int(input())
def inpl(): return list(map(int, input().split()))
def inpl_str(): return list(input().split())

def dfs(x,y,s,c):
    global tmpp
    if not(0<=x<W and 0<=y<H):
        return
    elif tmpp[y][x] != s:
        return
    else:
        tmpp[y][x] = c
        dfs(x+1,y,s,c)
        dfs(x-1,y,s,c)
        dfs(x,y+1,s,c)
        dfs(x,y-1,s,c)

def calc(x,y):
    global tmpp
    if not(0<=x<W and 0<=y<H):
        return 0
    elif tmpp[y][x] != C:
        return 0
    else:
        tmpp[y][x] = -1
        return calc(x+1,y) + calc(x-1,y) + calc(x,y+1) + calc(x,y-1) + 1



while True:
    H,W,C = inpl()
    if H == 0:
        break
    pp = [inpl() for _ in range(H)]
    ans = 0

    for arg in itertools.product(range(1,7),repeat=4):
        colors = list(arg) + [C]
        tmpp = [p[:] for p in pp]
        for c in colors:
            if tmpp[0][0] == c:
                continue
            else:
                dfs(0,0,tmpp[0][0],c)

        ans = max(calc(0,0),ans)

    print(ans)