$dx = [0,1,0,-1]
$dy = [1,0,-1,0]
def bfs(f, sy, sx, q, h, w, col, visited)
    for i in 0..3
        cy = sy + $dy[i]
        cx = sx + $dx[i]
        if cy.between?(0,h-1) && cx.between?(0,w-1) && f[cy][cx]== f[sy][sx] && !visited.include?([cy,cx])
            q.push([cy,cx])
            visited.push([cy,cx])
        end
    end
    f[sy][sx] = col
    while q.size > 0
        cy, cx = q.shift
        f = bfs(f,cy,cx,q,h,w,col,visited)
    end
    return f
end
def count(f, sy, sx, q, h, w, visited)
    c = 0
    for i in 0..3
        cy = sy + $dy[i]
        cx = sx + $dx[i]
        if cy.between?(0,h-1) && cx.between?(0,w-1) && f[cy][cx]== f[sy][sx] && !visited.include?([cy,cx])
            q.push([cy,cx])
            visited.push([cy,cx])
            c += 1
        end
    end
    while q.size > 0
        cy, cx = q.shift
        c += count(f,cy,cx,q,h,w,visited)
    end
    return c
end
loop do
    h, w, c = gets.split.map(&:to_i)
    break if h == 0 && w == 0 && c == 0
    p = h.times.map{gets.split.map(&:to_i)}
    o = (1..6).to_a.repeated_permutation(5).to_a
    o.select!{|od| od[0] == p[0][1] || od[0] == p[1][0]} if h > 1 && w > 1 && count(p,0,0,[],h,w,[]) == 1
    o.select!{|od| od[4] == c}
    max = 1
    o.each_with_index do |od, i|
        pp = Marshal.load(Marshal.dump(p))
        od.each do |col|
            pp = bfs(pp,0,0,[],h,w,col,[])
        end
        c = count(pp,0,0,[],h,w,[])
        max = c if c > max
    end
    puts max
end