#include <bits/stdc++.h>
using namespace std;
int n, m, x, ans;
char ch;
int rt[2 * 16390], tmp[16390];
int a[2][16390];
int find_rt(int h) { return rt[h] == h ? h : rt[h] = find_rt(rt[h]); }
void join(int x, int y) { rt[find_rt(x)] = find_rt(y); }
int main() {
  scanf("%d %d ", &n, &m);
  for (int i = 0; i < 2 * m; i++) rt[i] = i;
  for (int i = 0, t = 0, nt = 1; i < n; i++, t ^= 1, nt ^= 1) {
    for (int j = 0; j < m / 4; j++) {
      ch = getchar();
      x = (ch >= 'A' && ch <= 'Z') ? (ch - 'A' + 10) : ch - '0';
      for (int k = 0; k < 4; k++) {
        a[t][4 * j + 3 - k] = x & (1 << k);
      }
    }
    ch = getchar();
    for (int j = 0; j < m; j++) {
      if (!a[t][j]) continue;
      int l = m * t + j - 1, u = m * nt + j, h = m * t + j;
      if (j && a[nt][j] && a[t][j - 1]) {
        if (find_rt(l) != find_rt(u)) {
          ans--;
          join(l, h), join(u, h);
        } else
          join(l, h);
      } else if (j && a[t][j - 1])
        join(l, h);
      else if (a[nt][j])
        join(u, h);
      else
        ans++;
    }
    for (int j = 0; j < m; j++) {
      int h = m * t + j;
      find_rt(h);
      if (nt * m <= rt[h] && rt[h] < nt * m + m) {
        tmp[rt[h] % m] = j;
      }
    }
    for (int j = 0; j < m; j++) {
      int h = m * t + j;
      if (nt * m <= rt[h] && rt[h] < nt * m + m) rt[h] = tmp[rt[h] % m];
    }
    for (int j = 0; j < m; j++) rt[nt * m + j] = nt * m + j;
  }
  printf("%d\n", ans);
}
