#include <cassert>
#include <cstdio>
#include <cstring>

#define TASKNAME "covering"

const int MaxN = 9, MaxK = 3, MaxP = 12;

int a [MaxN + MaxK] [MaxN + MaxK];
bool b [MaxK] [MaxK];

int main (void)
{
 int i, j, k, m, n, p, q, u, v, x, y;
 int count, min, lim;
 bool ok;
 char c;
 freopen (TASKNAME ".in", "r", stdin);
 freopen (TASKNAME ".out", "w", stdout);
 while (scanf (" %d %d", &m, &n) != EOF)
 {
  assert (1 <= m && m <= MaxN);
  assert (1 <= n && n <= MaxN);
  for (i = 0; i < MaxK; i++)
   for (j = 0; j < MaxK; j++)
   {
    assert (scanf (" %c", &c) == 1);
    assert (c == 'X' || c == '.');
    b[j][i] = (c == 'X');
   }
  min = m * n + 1;
  for (x = 1; x <= MaxN; x++)
   for (y = 1; y <= MaxN; y++)
    if (x * y < MaxP)
    {
     lim = 1 << (x * y);
     for (u = 0; u < MaxK; u++)
      for (v = 0; v < MaxK; v++)
       for (k = lim - 1; k >= 0; k--)
       {
        memset (a, 0, sizeof (a));
        count = 0;
        for (i = 1; i <= m; i++)
         for (j = 1; j <= n; j++)
          if (k & (1 << (((i % y) * x) + (j % x))))
          {
           ok = false;
           for (p = 0; p < MaxK; p++)
            for (q = 0; q < MaxK; q++)
             if (!a[i + p][j + q] && b[p][q])
             {
              if (i + p >= u && i + p < m + u && j + q >= v && j + q < n + v)
               ok = true;
              a[i + p][j + q]++;
             }
           if (ok)
           count++;
          }
         for (i = 1; i <= m; i++)
          for (j = 1; j <= n; j++)
          if (k & (1 << (((i % y) * x) + (j % x))))
          {
           ok = false;
           for (p = 0; p < MaxK; p++)
            for (q = 0; q < MaxK; q++)
             if (a[i + p][j + q] == 1 && b[p][q])
              if (i + p >= u && i + p < m + u && j + q >= v && j + q < n + v)
               ok = true;
           if (!ok)
           {
            for (p = 0; p < MaxK; p++)
             for (q = 0; q < MaxK; q++)
              if (b[p][q])
               a[i + p][j + q]--;
            count--;
           }
          }
         ok = true;
         for (i = u; i < m + u; i++)
          for (j = v; j < n + v; j++)
           ok &= a[i][j];
         if (ok)
          if (min > count)
           min = count;
       }
    }
  printf ("%d\n", min);
 }
 return 0;
}
