### constant

CS = ['J', 'O', 'I']
CHASH = {'J' => 0, 'O' => 1, 'I' => 2}

### main

m, n = gets.strip.split(' ').map(&:to_i)

flags = []

m.times do
  flags << gets.strip
end
#p flags

e00, e01 = gets.strip.split('')
e10, e11 = gets.strip.split('')

count = 0

for y in (0...(m - 1))
  for x in (0...(n - 1))
    if flags[y][x] == e00 && flags[y][x + 1] == e01 &&
        flags[y + 1][x] == e10 && flags[y + 1][x + 1] == e11
      count += 1
    end
  end
end
#p count

max_plus = 0

for y in (0...m)
  for x in (0...n)
    c0 = flags[y][x]
    pluses = [0] * 3

    for i in (0..2)
      c = CS[i]
      if y > 0
        if x > 0 &&
            flags[y - 1][x - 1] == e00 && flags[y - 1][x] == e01 &&
            flags[y][x - 1] == e10 && c == e11
          pluses[i] += 1
        end
        if x < n - 1 &&
            flags[y - 1][x] == e00 && flags[y - 1][x + 1] == e01 &&
             c == e10 && flags[y][x + 1] == e11
          pluses[i] += 1
        end
      end
      if y < m - 1
        if x > 0 &&
            flags[y][x - 1] == e00 && c == e01 &&
            flags[y + 1][x - 1] == e10 && flags[y + 1][x] == e11
          pluses[i] += 1
        end
        if x < n - 1 &&
            c == e00 && flags[y][x + 1] == e01 &&
            flags[y + 1][x] == e10 && flags[y + 1][x + 1] == e11
          pluses[i] += 1
        end
      end
    end

    plus = pluses.max - pluses[CHASH[c0]]
    max_plus = plus if max_plus < plus
  end
end
#p max_plus

puts (count + max_plus)