def count(mask, l, r):
cnt = 0
for i in range(l, r):
if (mask & (1 << i)) != 0:
cnt += 1
return cnt
def dist(A, B):
x1, y1 = A
x2, y2 = B
return abs(x1 - x2) + abs(y1 - y2)
n, m, k = map(int, input().split())
start = (0, 0)
mines = []
journ = []
for i in range(n):
s = input()
for j in range(m):
if s[j] == 'P':
start = (i, j)
if s[j] == 'M':
mines.append((i, j))
if s[j] == 'J':
journ.append((i, j))
ALL = mines + journ
INF = int(1e9)
dp = [[INF for i in range(2 * k)] for j in range(1 << (2 * k))]
for i in range(k):
dp[1 << i][i] = dist(start, mines[i])
for mask in range(1 << (2 * k)):
visited_mines = count(mask, 0, k)
visited_journ = count(mask, k, 2 * k)
if visited_mines > 1 + visited_journ or visited_journ > visited_mines:
continue
for pos in range(2 * k):
if (mask & (1 << pos)) == 0:
continue
for prev in range(2 * k):
if (mask & (1 << prev)) == 0 or (prev < k) == (pos < k):
continue
dp[mask][pos] = min(dp[mask][pos], dp[mask ^ (1 << pos)][prev] + dist(ALL[prev], ALL[pos]))
ans = INF
for pos in range(k, 2 * k):
ans = min(ans, dp[(1 << (2 * k)) - 1][pos])
print(ans)