import std.stdio;
import std.c.stdio;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.regex;
import std.typecons;
 
void main() {
    int H, W; readf("%d %d\n", &H, &W);
    char[][] F;
    for (int i = 0; i < H; i++) {
        F ~= cast(char[])readln.chomp;
    }
    char[][] P;
    for (int i = 0; i < 2; i++) {
        P ~= cast(char[])readln.chomp;
    }
    string X = "JOI";
    int Ans = 0;
    int C() {
        int Count = 0;
        bool M(int h, int w) {
            for (int y = 0; y < 2; y++) 
                for (int x = 0; x < 2; x++) 
                    if (F[h + y][w + x] != P[y][x]) return false;
            return true;
        }
        for (int h = 0; h < H - 1; h++) {
            for (int w = 0; w < W - 1; w++) {
                if (M(h, w)) {
                    Count++;
                }
            }
        }
        return Count;
    }
    for (int h = 0; h < H; h++) {
        for (int w = 0; w < W; w++) {
            for (int i = 0; i < 3; i++) {
                char t = F[h][w];
                F[h][w] = X[i];
                Ans = max(Ans, C());
                F[h][w] = t;
            }
        }
    }
    printf("%d\n", Ans);
}