#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
const int MOD=1e9+7;

int main(void){
    int h,w;
    cin>>h>>w;
    vector<string> M(h);
    rep(i,h) cin>>M[i];
    queue<pair<int,int>> que;
    vector<vector<int>> seen(h,vector<int>(w,-1));
    rep(i,h) rep(j,w){
        if(M[i][j]=='#'){
            que.push(make_pair(i,j));
            seen[i][j]=0;
        }
    }
    int dx[]={1,0,-1,0};
    int dy[]={0,1,0,-1};
    while(!que.empty()){
        int x=que.front().first;
        int y=que.front().second;
        que.pop();
        rep(dir,4){
            int nx=x+dx[dir];
            int ny=y+dy[dir];
            if(nx<0 || nx>=h || ny<0 ||ny>=w) continue;
            if(seen[nx][ny]!=-1) continue;
            seen[nx][ny]=seen[x][y]+1;
            que.push(make_pair(nx,ny));
        }
    }
    
    int ans=0;
    rep(i,h){
        rep(j,w){
            //cout<<seen[i][j]<<" ";
            ans=max(ans,seen[i][j]);
        }
        //cout<<endl;
    }
    cout<<ans<<endl;
}
#include <bits/stdc++.h>
#include <numeric>
#define rep(i,n) for (int i = 0; i < n; ++i)
#define per(i,n) for (int i = n - 1; i >= 0; --i)
#define rep1(i,n) for (int i = 1; i <= n; ++i)
template<typename T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }
template<typename T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<typename T> inline T intceil(T a, T b) { return (a + (b - 1)) / b; }
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int,int> P;
typedef pair<ll,ll> PL;
const long long MOD = 1e9+7;
#define precout() cout << std::fixed << std::setprecision(20);
const string alphabet = "abcdefghijklmnopqrstuvwxyz";
const int dy[4] = { 0, 1, 0, -1 };
const int dx[4] = { 1, 0, -1, 0 };
static const double pi = 3.141592653589793;

int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);

  int n; cin >> n;
  ll prev; cin >> prev;
  bool ok = 1;

  if(prev > 0) {
    ok = 0;
  }

  ll ans = 0;
  rep(i, n - 1) {
    ll tmp; cin >> tmp;
    if(!ok) continue;

    if(tmp == 0) {
      prev = tmp;
      continue;
    }

    ll diff = tmp - prev;
    if(diff > 1) {
      ok = 0;
      continue;
    }

    if(diff == 1) {
      ++ans;
    } else {
      ans += tmp;
    }

    prev = tmp;
  }

  if(ok) {
    cout << ans << endl;
  } else {
    cout << -1 << endl;
  }
}
