require 'set'
def f(a, c, n, prev_group_size = 0)
    g = group(a, 0, 0)
    return g.size if n == 0

    return g.size if g.size <= prev_group_size

    max = 0
    (n == 1 ? [c] : (1..6).to_a - [a[0][0]]).each do |k|
        b = (0..a.size-1).map do |i|
            (0..a[0].size-1).map do |j|
                g.include?([i, j]) ? k : a[i][j]
            end
        end
        m = f(b, c, n-1, g.size)
        max = m if m > max
    end
    max
end

def group(a, i, j)
    reached = Set[[i, j]]
    stack = [[i, j]]
    until stack.empty?
        y, x = stack.pop
        [[1, 0], [-1, 0], [0, 1], [0, -1]].each do |dy, dx|
            v, u = y + dy, x + dx
            next if v < 0 || v >= a.size || u < 0 || u >= a[0].size
            next if a[v][u] != a[i][j]
            pos = [v, u]
            next if reached.include?(pos)
            reached << pos
            stack << pos
        end
    end
    reached
end

loop do
    h, w, c = gets.split.map(&:to_i)
    break if h == 0
    a = (1..h).map { gets.split.map(&:to_i) }
    p f(a, c, 5)
end