#include <bits/stdc++.h>
using namespace std;
int n, m;
int raiz(int padre[], int nodo) {
  if (padre[nodo] == 0)
    return nodo;
  else
    return padre[nodo] = raiz(padre, padre[nodo]);
}
long long int componentes(int l, int r, int sup[], int inf[]) {
  if (l > r) {
    fill(sup, sup + m, 0);
    fill(inf, inf + m, 0);
    return 0;
  } else if (l == r) {
    int cnt = 0, ant = 0, idx = 0;
    for (int c = 0; c < m / 4; c++) {
      char x;
      int num;
      cin >> x;
      num = x >= '0' && x <= '9' ? x - '0' : x - 'A' + 10;
      for (int k = 3; k >= 0; k--) {
        if (num & (1 << k))
          sup[idx] = inf[idx] = ant == 1 ? cnt : ++cnt;
        else
          sup[idx] = inf[idx] = 0;
        ant = num & (1 << k) ? 1 : 0;
        idx++;
      }
    }
    return cnt;
  } else {
    int med = (l + r) / 2;
    int infA[m], supB[m];
    long long int ans = componentes(l, med, sup, infA);
    ans += componentes(med + 1, r, supB, inf);
    int root[4 * m];
    fill(root, root + 4 * m, 0);
    for (int i = 0; i < m; i++) {
      int nodop = infA[i], nodoq = supB[i] + 2 * m;
      if (infA[i] > 0 && supB[i] > 0) {
        if (raiz(root, nodop) != raiz(root, nodoq)) {
          ans--;
          root[raiz(root, nodoq)] = raiz(root, nodop);
        }
      }
    }
    for (int i = 0; i < m; i++) {
      if (sup[i] != 0) sup[i] = raiz(root, sup[i]);
      if (infA[i] != 0) infA[i] = raiz(root, infA[i]);
      if (supB[i] != 0) supB[i] = raiz(root, supB[i] + 2 * m);
      if (inf[i] != 0) inf[i] = raiz(root, inf[i] + 2 * m);
    }
    fill(root, root + 2 * m, 0);
    int cnt = 0;
    for (int i = 0; i < m; i++) {
      if (sup[i] == 0) continue;
      if (root[sup[i]] == 0) root[sup[i]] = ++cnt;
      sup[i] = root[sup[i]];
    }
    for (int i = 0; i < m; i++) {
      if (inf[i] == 0) continue;
      if (root[inf[i]] == 0) root[inf[i]] = ++cnt;
      inf[i] = root[inf[i]];
    }
    return ans;
  }
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cin >> n >> m;
  int sup[m], inf[m];
  int ans = componentes(0, n - 1, sup, inf);
  cout << ans << "\n";
  return 0;
}
