m, n = gets.split.map &:to_i
f = (1..m).map { gets.chomp }
e = gets.chomp.split("") + gets.chomp.split("")

hash = {}

count = 0
(0..m-2).each{|i|
	(0..n-2).each{|j|
		a = [
			f[i][j] == e[0],
			f[i][j+1] == e[1],
			f[i+1][j] == e[2],
			f[i+1][j+1] == e[3],
		]
		case a.count{|b| b}
		when 4
			count += 1
			[[i,j], [i,j+1], [i+1,j], [i+1,j+1]].each{|y, x|
				pos = [y, x]
				hash[pos] ||= Hash.new(0)
				(%w(J O I) - [f[i][j]]).each{|c|
					hash[pos][c] -= 1
				}
			}
		when 3
			k = a.index{|b| !b}
			pos = [i + k/2, j + k%2]
			hash[pos] ||= Hash.new(0)
			hash[pos][e[k]] += 1
		end
	}
}

p count + [hash.values.map(&:values).flatten.max || 0, 0].max