/*WELCOME TO AYUSH RANJAN CODE'S*/
/*EVERY PROBLEM HAS A SOLUTION SOMETIMES ELEGENT OTHERWISE COMPLEX ELEGENCE*/

#include <bits/stdc++.h>
using namespace std;
int chkpower2(int x){
    return (x&&!(x&x-1));
}

void solve(){
    int n;
    cin>>n;
    int a[n];
    for(int i1=0;i1<n;i1++){
        cin>>a[i1];
    }
   long long int i1=1,maxt=a[0],ans=0;
    while(i1<n){
        if(a[i1]>=maxt){
            maxt=a[i1];
            i1++;
            continue;
        }
        else{
            vector<int> v1;
            while(a[i1]<maxt){
                    if(i1>=n){
                        break;
                    }
                   // cout<<a[i1]<<" ";
                v1.push_back(a[i1]);
                i1++;
                if(i1>=n){
                    break;
                }
            }
            sort(v1.begin(),v1.end());
            ans+=maxt-v1[v1.size()-1];
           // cout<<v1.size()<<" ";
            for(int i2=v1.size()-1;i2>0;i2--){
                  //  cout<<i2<<" "<<i2-1<<endl;
                    ans+=v1[i2]-v1[i2-1];
            }
        }
    }
    cout<<ans;
}

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

    int t;
    t=1;//cin>>t;
    while(t--){
        solve();
        cout<<"\n";
    }
    return 0;
}


/*WELCOME TO AYUSH RANJAN CODE'S*/
/*EVERY PROBLEM HAS A SOLUTION SOMETIMES ELEGENT OTHERWISE COMPLEX ELEGENCE*/

#include <bits/stdc++.h>
using namespace std;
int chkpower2(int x){
    return (x&&!(x&x-1));
}

void solve(){
    int n;
    cin>>n;
    int a[n];
    for(int i1=0;i1<n;i1++){
        cin>>a[i1];
    }
    int i1=1,maxt=a[0],ans=0;
    while(i1<n){
        if(a[i1]>=maxt){
            maxt=a[i1];
            i1++;
            continue;
        }
        else{
            vector<int> v1;
            while(a[i1]<maxt){
                    if(i1>=n){
                        break;
                    }
                   // cout<<a[i1]<<" ";
                v1.push_back(a[i1]);
                i1++;
            }
            sort(v1.begin(),v1.end());
            ans+=maxt-v1[v1.size()-1];
           // cout<<v1.size()<<" ";
            for(int i2=v1.size()-1;i2>0;i2--){
                  //  cout<<i2<<" "<<i2-1<<endl;
                    ans+=v1[i2]-v1[i2-1];
            }
        }
    }
    cout<<ans;
}

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

    int t;
    t=1;//cin>>t;
    while(t--){
        solve();
        cout<<"\n";
    }
    return 0;
}


/*WELCOME TO AYUSH RANJAN CODE'S*/
/*EVERY PROBLEM HAS A SOLUTION SOMETIMES ELEGENT OTHERWISE COMPLEX ELEGENCE*/

#include <bits/stdc++.h>
using namespace std;
int chkpower2(int x){
    return (x&&!(x&x-1));
}

void solve(){
    int n;
    cin>>n;
    int a[n];
    for(int i1=0;i1<n;i1++){
        cin>>a[i1];
    }
   long long int i1=1,maxt=a[0],ans=0;
    while(i1<n){
        if(a[i1]>=maxt){
            maxt=a[i1];
            i1++;

            continue;
        }
        else{
            vector<int> v1;
            while(a[i1]<maxt){
                    if(i1>=n){
                        break;
                    }
                   // cout<<a[i1]<<" ";
                v1.push_back(a[i1]);
                i1++;
            }
            sort(v1.begin(),v1.end());
            ans+=maxt-v1[v1.size()-1];
           // cout<<v1.size()<<" ";
            for(int i2=v1.size()-1;i2>0;i2--){
                  //  cout<<i2<<" "<<i2-1<<endl;
                    ans+=v1[i2]-v1[i2-1];
            }
        }
    }
    cout<<ans;
}

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

    int t;
    t=1;//cin>>t;
    while(t--){
        solve();
        cout<<"\n";
    }
    return 0;
}


/*WELCOME TO AYUSH RANJAN CODE'S*/
/*EVERY PROBLEM HAS A SOLUTION SOMETIMES ELEGENT OTHERWISE COMPLEX ELEGENCE*/

#include <bits/stdc++.h>
using namespace std;
int chkpower2(int x){
    return (x&&!(x&x-1));
}

void solve(){
    int n;
    cin>>n;
    int a[n];
    for(int i1=0;i1<n;i1++){
        cin>>a[i1];
    }
    long long ans=0;
    for(int i1=1;i1<n;i1++){
        if(a[i1]>=a[i1-1]){
            continue;
        }
        else{
            ans+=a[i1-1]-a[i1];
        }
    }
    cout<<ans;
}

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

    int t;
   t=1;//cin>>t;
    while(t--){
        solve();
        cout<<"\n";
    }
    return 0;
}


/*WELCOME TO AYUSH RANJAN CODE'S*/
/*EVERY PROBLEM HAS A SOLUTION SOMETIMES ELEGENT OTHERWISE COMPLEX ELEGENCE*/

#include <bits/stdc++.h>
using namespace std;
int chkpower2(int x){
    return (x&&!(x&x-1));
}

void solve(){
    int n;
    cin>>n;
    int a[n];
    for(int i1=0;i1<n;i1++){
        cin>>a[i1];
    }
   long long int i1=1,maxt=a[0],ans=0;
    while(i1<n){
        if(a[i1]>=maxt){
            maxt=a[i1];
            i1++;
            continue;
        }
        else{
            vector<int> v1;
            while(a[i1]<maxt){
                    if(i1>=n){
                        break;
                    }
                   // cout<<a[i1]<<" ";
                v1.push_back(a[i1]);
                i1++;
            }
            sort(v1.begin(),v1.end());
            ans+=maxt-v1[v1.size()-1];
           // cout<<v1.size()<<" ";
            for(int i2=v1.size()-1;i2>0;i2--){
                    cout<<i2<<" "<<i2-1<<endl;
                    ans+=v1[i2]-v1[i2-1];
            }
        }
    }
    cout<<ans;
}

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

    int t;
    t=1;//cin>>t;
    while(t--){
        solve();
        cout<<"\n";
    }
    return 0;
}


#include<bits/stdc++.h>
#define fastAF ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define ll long long
#define ull unsigned ll
#define ld long double
#define pb emplace_back
#define pf push_front
#define dll deque<ll>
#define vll vector<ll>
#define pll pair<ll,ll>
#define mapll map<ll,ll>
#define endl "\n"
#define all(v) v.begin(),v.end()
#define deb(x) cout<<x
#define mod (int) 1e9+7
#define pi 3.1415926536
#define deci(x) setprecision(x)
#define  rev greater<int>()
using namespace std;
int main()
{
	ll int n;
    cin>>n;
    ll int a[n];
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    ll int i=0,j=1;
    vll v;
    while(i<n){
        if(a[i]>a[j]&&i<n-1&&j<n){
            v.pb(i);
            j=i+1;
        while(a[i]>a[j]&&i<n&&j<n){
         j++;
        }
        v.pb(j);
        i=j;
        j++;
        //cout<<v[i]<<" "<<v[j]<<endl;
        }else{
            i++;
            j++;
        }
    }
    ll int moves=0,m=INT32_MAX;
    //cout<<v.size()<<endl;
    if(v.size()>0){
    for(int i=0;i<v.size();i+=2){
        m=INT32_MAX;
        for(int j=v[i]+1;j<v[i+1];j++){
            m=min(m,a[j]);
        }
      //  cout<<m<<endl;
        moves+=a[v[i]]-m;
    }
    }
    cout<<moves<<endl;
}


#include<bits/stdc++.h>
#define fastAF ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define ll long long
#define ull unsigned ll
#define ld long double
#define pb emplace_back
#define pf push_front
#define dll deque<ll>
#define vll vector<ll>
#define pll pair<ll,ll>
#define mapll map<ll,ll>
#define endl "\n"
#define all(v) v.begin(),v.end()
#define deb(x) cout<<x
#define mod (int) 1e9+7
#define pi 3.1415926536
#define deci(x) setprecision(x)
#define  rev greater<int>()
using namespace std;
int main()
{
	ll int n;
    cin>>n;
    ll int a[n];
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    ll int i=0,j=1;
    vll v;
    while(i<n){
        if(i<n-1&&j<n&&a[i]>a[j]){
            v.pb(i);
            j=i+1;
        while(i<n-1&&j<n&&a[i]>a[j]){
         j++;
        }
        v.pb(j);
        i=j;
        j++;
        //cout<<v[i]<<" "<<v[j]<<endl;
        }else{
            i++;
            j++;
        }
    }
    ll int moves=0,m=INT32_MAX;
    //cout<<v.size()<<endl;
    if(v.size()>0){
    for(int i=0;i<v.size();i+=2){
        m=INT32_MAX;
        for(int j=v[i]+1;j<v[i+1];j++){
            m=min(m,a[j]);
        }
      //  cout<<m<<endl;
        moves+=a[v[i]]-m;
    }
    }
    cout<<moves<<endl;
}


#include<bits/stdc++.h>
#define fastAF ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define ll long long
#define ull unsigned ll
#define ld long double
#define pb emplace_back
#define pf push_front
#define dll deque<ll>
#define vll vector<ll>
#define pll pair<ll,ll>
#define mapll map<ll,ll>
#define endl "\n"
#define all(v) v.begin(),v.end()
#define deb(x) cout<<x
#define mod (int) 1e9+7
#define pi 3.1415926536
#define deci(x) setprecision(x)
#define  rev greater<int>()
using namespace std;
int main()
{
	ll int n;
    cin>>n;
    ll int a[n];
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    ll int i=0,j=1;
    vll v;
    while(i<n){
        if(a[i]>a[j]&&i<n-1&&j<n){
            v.pb(i);
        while(a[i]>a[j]&&i<n&&j<n){
         j++;
        }
        v.pb(j);
        i=j;
        j++;
        }else{
            i++;
        }
    }
    ll int moves=0,m=INT32_MAX;
    if(v.size()>0){
    for(int i=0;i<v.size();i+=2){
        m=INT32_MAX;
        for(int j=v[i]+1;j<v[i+1];j++){
            m=min(m,a[j]);
        }
        moves+=a[v[i]]-m;
    }
    }
    cout<<moves<<endl;
}


#include<bits/stdc++.h>
#define fastAF ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define ll long long
#define ull unsigned ll
#define ld long double
#define pb emplace_back
#define pf push_front
#define dll deque<ll>
#define vll vector<ll>
#define pll pair<ll,ll>
#define mapll map<ll,ll>
#define endl "\n"
#define all(v) v.begin(),v.end()
#define deb(x) cout<<x
#define mod (int) 1e9+7
#define pi 3.1415926536
#define deci(x) setprecision(x)
#define  rev greater<int>()
using namespace std;
int main()
{
	ll int n;
    cin>>n;
    ll int a[n];
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    ll int i=0,j=1;
    vll v;
    while(i<n){
        if(a[i]>a[j]&&i<n-1&&j<n){
            v.pb(i);
            j=i+1;
        while(a[i]>a[j]&&i<n&&j<n){
         j++;
        }
        v.pb(j);
        i=j;
        j++;
        //cout<<v[i]<<" "<<v[j]<<endl;
        }else{
            i++;
            j++;
        }
    }
    ll int moves=0,m=INT32_MAX;
    //cout<<v.size()<<endl;
    if(v.size()>0){
    for(int i=0;i<v.size();i+=2){
        m=INT32_MAX;
        for(int j=v[i]+1;j<v[i+1];j++){
            m=min(m,a[j]);
        }
        cout<<m<<endl;
        moves+=a[v[i]]-m;
    }
    }
    cout<<moves<<endl;
}


#include<bits/stdc++.h>
#define fastAF ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define ll long long
#define ull unsigned ll
#define ld long double
#define pb emplace_back
#define pf push_front
#define dll deque<ll>
#define vll vector<ll>
#define pll pair<ll,ll>
#define mapll map<ll,ll>
#define endl "\n"
#define all(v) v.begin(),v.end()
#define deb(x) cout<<x
#define mod (int) 1e9+7
#define pi 3.1415926536
#define deci(x) setprecision(x)
#define  rev greater<int>()
using namespace std;
int main()
{
	ll int n;
    cin>>n;
    ll int a[n];
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    ll int i=0,j=1;
    vll v;
    while(i<n){
        if(a[i]>a[j]&&i<n-1&&j<n){
            v.pb(i);
        while(a[i]>a[j]&&i<n&&j<n){
         j++;
        }
        v.pb(j);
        i=j;
        j++;
        //cout<<v[i]<<" "<<v[j]<<endl;
        }else{
            i++;
            j++;
        }
    }
    ll int moves=0,m=INT32_MAX;
    //cout<<v.size()<<endl;
    if(v.size()>0){
    for(int i=0;i<v.size();i+=2){
        m=INT32_MAX;
        for(int j=v[i]+1;j<v[i+1];j++){
            m=min(m,a[j]);
        }
        moves+=a[v[i]]-m;
    }
    }
    cout<<moves<<endl;
}


#include<bits/stdc++.h>
#define fastAF ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define ll long long
#define ull unsigned ll
#define ld long double
#define pb emplace_back
#define pf push_front
#define dll deque<ll>
#define vll vector<ll>
#define pll pair<ll,ll>
#define mapll map<ll,ll>
#define endl "\n"
#define all(v) v.begin(),v.end()
#define deb(x) cout<<x
#define mod (int) 1e9+7
#define pi 3.1415926536
#define deci(x) setprecision(x)
#define  rev greater<int>()
using namespace std;
int main()
{
	ll int n;
    cin>>n;
    ll int a[n];
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    ll int i=0,j=1;
    vll v;
    while(i<n){
        if(a[i]>a[j]&&i<n-1&&j<n){
            v.pb(i);
            j=i+1;
        while(a[i]>a[j]&&i<n-1&&j<n){
         j++;
        }
        v.pb(j);
        i=j;
        j++;
        //cout<<v[i]<<" "<<v[j]<<endl;
        }else{
            i++;
            j++;
        }
    }
    ll int moves=0,m=INT32_MAX;
    //cout<<v.size()<<endl;
    if(v.size()>0){
    for(int i=0;i<v.size();i+=2){
        m=INT32_MAX;
        for(int j=v[i]+1;j<v[i+1];j++){
            m=min(m,a[j]);
        }
      //  cout<<m<<endl;
        moves+=a[v[i]]-m;
    }
    }
    cout<<moves<<endl;
}


#include<bits/stdc++.h>
#define fastAF ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define ll long long
#define ull unsigned ll
#define ld long double
#define pb emplace_back
#define pf push_front
#define dll deque<ll>
#define vll vector<ll>
#define pll pair<ll,ll>
#define mapll map<ll,ll>
#define endl "\n"
#define all(v) v.begin(),v.end()
#define deb(x) cout<<x
#define mod (int) 1e9+7
#define pi 3.1415926536
#define deci(x) setprecision(x)
#define  rev greater<int>()
using namespace std;
int main()
{
	ll int n,m1,m=0;
    cin>>n;
    ll int a[n];
    cin>>a[0];
    m1=a[0];
    for(int i=1;i<n;i++){
        cin>>a[i];
        if(m1>a[i]){
            m+=a[i-1]-a[i];
        }
        m1=a[i];
    }
    cout<<m<<endl;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
	int n;
	cin>>n;
	long long int arr[n];
	long long int largest;
	long long int dp[n];
	long long int total=0;
	for(int i=0;i<n;i++)
	{
		cin>>arr[i];
		if(i==0)
			largest=arr[i];
		else
		{
			if(arr[i]>largest)
				largest=arr[i];
		}
		dp[i]=largest;

		if(i>0)
		{
			if(largest>dp[i-1])
			{	int index=-1;
				for(int j=i-1;j>=0;j--)
				{
					if(dp[j]==dp[i-1])
						index=j;
				}
				vector<long long int> v1;
				for(int j=i-1;j>index;j--)
				{
					v1.push_back(arr[j]);
				}
				sort(v1.begin(),v1.end());
				reverse(v1.begin(),v1.end());
				long long int curr=0;
				for(int j=0;j<v1.size();j++)
				{	//cout<<v1[j]<<" ";
					v1[j]=v1[j]+curr;
					total=total+dp[i-1]-v1[j];

					curr=dp[i-1]-v1[j];

				}
				//cout<<endl;

			}
			else if(i==(n-1))
			{

				int index=-1;
				for(int j=i;j>=0;j--)
				{
					if(dp[j]==dp[i])
						index=j;
				}
				vector<long long int> v1;
				for(int j=i;j>index;j--)
				{
					v1.push_back(arr[j]);
				}
				sort(v1.begin(),v1.end());
				reverse(v1.begin(),v1.end());
				long long int curr=0;
				for(int j=0;j<v1.size();j++)
				{	//cout<<v1[j]<<" ";
					v1[j]=v1[j]+curr;
					total=total+dp[i]-v1[j];

					curr=dp[i]-v1[j];

				}
				//cout<<endl;

			}

			}
		}cout<<total;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
	int n;
	cin>>n;
	int arr[n];
	int largest;
	int dp[n];
	int total=0;
	for(int i=0;i<n;i++)
	{
		cin>>arr[i];
		if(i==0)
			largest=arr[i];
		else
		{
			if(arr[i]>largest)
				largest=arr[i];
		}
		dp[i]=largest;

		if(i>0)
		{
			if(largest>dp[i-1])
			{	int index=-1;
				for(int j=i-1;j>=0;j--)
				{
					if(dp[j]==dp[i-1])
						index=j;
				}
				vector<int> v1;
				for(int j=i-1;j>index;j--)
				{
					v1.push_back(arr[j]);
				}
				sort(v1.begin(),v1.end());
				reverse(v1.begin(),v1.end());
				int curr=0;
				for(int j=0;j<v1.size();j++)
				{	//cout<<v1[j]<<" ";
					v1[j]=v1[j]+curr;
					total=total+dp[i-1]-v1[j];

					curr=dp[i-1]-v1[j];

				}
				//cout<<endl;

			}
			else if(i==(n-1))
			{

				int index=-1;
				for(int j=i;j>=0;j--)
				{
					if(dp[j]==dp[i])
						index=j;
				}
				vector<int> v1;
				for(int j=i;j>index;j--)
				{
					v1.push_back(arr[j]);
				}
				sort(v1.begin(),v1.end());
				reverse(v1.begin(),v1.end());
				int curr=0;
				for(int j=0;j<v1.size();j++)
				{	//cout<<v1[j]<<" ";
					v1[j]=v1[j]+curr;
					total=total+dp[i]-v1[j];

					curr=dp[i]-v1[j];

				}
				//cout<<endl;

			}

			}
		}cout<<total;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
	int n;
	cin>>n;
	long long int arr[n];
	long long int largest;
	long long int dp[n];
	long long int total=0;
	for(int i=0;i<n;i++)
	{
		cin>>arr[i];
		if(i==0)
			largest=arr[i];
		else
		{
			if(arr[i]>largest)
				largest=arr[i];
		}
		dp[i]=largest;

		if(i>0)
		{
			if(largest>dp[i-1])
			{	int index=-1;
				for(int j=i-1;j>=0;j--)
				{
					if(dp[j]==dp[i-1])
						index=j;
				}
				vector<long long int> v1;
				for(int j=i-1;j>index;j--)
				{
					v1.push_back(arr[j]);
				}
				sort(v1.begin(),v1.end());
				reverse(v1.begin(),v1.end());
				long long int curr=0;
				for(int j=0;j<v1.size();j++)
				{	//cout<<v1[j]<<" ";
					v1[j]=v1[j]+curr;
					total=total+dp[i-1]-v1[j];

					curr=dp[i-1]-v1[j];

				}
				//cout<<endl;

			}
			else if(i==(n-1))
			{

				int index=-1;
				for(int j=i;j>=0;j--)
				{
					if(dp[j]==dp[i])
						index=j;
				}
				vector<long long int> v1;
				for(int j=i;j>index;j--)
				{
					v1.push_back(arr[j]);
				}

				reverse(v1.begin(),v1.end());
				long long int curr=0;

				for(int j=0;j<v1.size();j++)
				{	//cout<<v1[j]<<" ";
					v1[j]=v1[j]+curr;
					total=total+dp[i]-v1[j];

					curr=dp[i]-v1[j];

				}
				//cout<<endl;

			}

			}
		}cout<<total;
}


#include<bits/stdc++.h>
using namespace std;
#define int long long int
main()
{
	int n;
	cin>>n;
	int arr[n];
	for(int i=0;i<n;i++)
	{
		cin>>arr[i];
	}
	int turns=0;
	int prev=arr[0];
	for(int i=1;i<n;i++)
	{

		if((arr[i]+turns)>=prev)
		{
			//do nothing
		}
		else
		{
			int tt=prev-(arr[i]+turns);
			turns+=tt;
		}
		prev=arr[i]+turns;
		//cout<<prev<<" "<<turns<<endl;
	}
	cout<<turns;
}


#define INF 2000000000

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <memory.h>
#include <algorithm>
#include <queue>
#include <stack>
#include <list>
#include <vector>

using namespace std;

int n;
long long ans = 0, a, b;

int main(){
#ifndef ONLINE_JUDGE
	freopen("input.txt","r",stdin);
	freopen("output.txt","w",stdout);
#endif

	scanf("%d", &n);
	cin>>a;
	for (int i=1; i<n; ++i){
		cin>>b;
		if (a > b + ans) ans = a - b;

		a = b + ans;
	}

	cout<<ans;

	return 0;
}


#include<bits/stdc++.h>
#define ll          long long
#define hell        1000000007
//#define ios        	ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
int main()
{
    int n,i,j;
    cin>>n;ll ans=0;
    ll a[n];ll b[n+1];b[0]=0;b[n]=0;
    for(i=0;i<n;i++) cin>>a[i];
    ll prev=a[0];
    for(i=1;i<n;i++)
    {
        if(a[i]<prev)
        b[i]=prev-a[i];
        else
        {
            b[i]=0;
            prev=a[i];
        }
    }
    for(i=1;i<n+1;i++)
    { ll mx=0;
        while(b[i]!=0)
        {
            mx=max(mx,b[i]);i++;
        }
        ans+=mx;

    }
    cout<<ans;
   // for(i=0;i<n;i++)
    //cout<<" "<<b[i];
    return 0;
}


#include<bits/stdc++.h>
#define ll          long long
#define hell        1000000007
//#define ios        	ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
int main()
{
    int n,i,j;
    cin>>n;ll ans=0;
    ll a[n];ll b[n+1];b[0]=0;b[n]=0;
    for(i=0;i<n;i++) cin>>a[i];
    ll prev=a[0];
    for(i=1;i<n;i++)
    {
        if(a[i]<=prev)
        b[i]=prev-a[i];
        else
        {
            b[i]=0;
            prev=a[i];
        }
    }
    for(i=1;i<n+1;i++)
    { ll mx=0;
        while(b[i]!=0)
        {
            mx=max(mx,b[i]);i++;
        }
        ans+=mx;
        i++;
    }
    cout<<ans;
    return 0;
}


//Incomplete
#include<bits/stdc++.h>
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL)
using namespace std;

int main()
{
    fastio;
    long long n,i,ara[100002],ans=0,p,mx,dif=0;
    cin>>n;
    for(i=0;i<n;i++)
        cin>>ara[i];
    for(i=0;i<n;i++)
    {
        if(i==0)
            mx=ara[i];
        else
        {
            if(ara[i]<mx)
            {
                dif=max(dif,mx-ara[i]);
            }
            else if(ara[i]>=mx)
            {
                mx=ara[i];
                ans=ans+dif;
                dif=0;
            }
        }
    }
    ans=ans+dif;
    cout<<ans;
    return 0;
}


//Incomplete
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
    long long n,i,ara[100001],b[100001],dif=0,m,j,p=0,k;
    cin>>n;
    for(i=0;i<n;i++)
        cin>>ara[i];
    for(i=0;i<n;i++)
        b[i]=ara[i];
    sort(b,b+n);
    for(i=n-1;i>0;i--)
    {
        if(ara[i]!=b[i])
            break;
    }
    m=b[i];
    j=i;
    for(i=0;i<=j;i++)
    {
        while(ara[i]<m)
        {
            p=max(p,m-ara[i]);
            //cout<<p<<"\n";
            break;
        }
        if(ara[i]==m)
        {
            dif=dif+p;
            p=0;
        }
        else if(i==j)
            dif=dif+p;
    }
    cout<<dif<<"\n";
    return 0;
}


#include<bits/stdc++.h>
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL)
using namespace std;

int main()
{
    fastio;
    long long n,i,ara[100002],ans=0;
    cin>>n;
    for(i=0;i<n;i++)
        cin>>ara[i];
    if(n==1)
        ans=0;
    else
    {
        for(i=0;i<n-1;i++)
        {
            if(ara[i]>ara[i+1])
            {
                ans=ans+ara[i]-ara[i+1];
            }
        }
    }
    cout<<ans;
    return 0;
}


#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
    long long n,i,ara[100001],b[100001],dif;
    cin>>n;
    for(i=0;i<n;i++)
        cin>>ara[i];
    for(i=0;i<n;i++)
        b[i]=ara[i];
    sort(b,b+n);
    for(i=n-1;i>0;i--)
    {
        if(ara[i]!=b[i])
            break;
    }
    dif=b[i]-b[0];
    cout<<dif<<"\n";
    return 0;
}


#include <bits/stdc++.h>

using namespace std;

typedef long long int LL;

#define st first
#define nd second
#define PLL pair <LL, LL>
#define PII pair <int, int>

const int N = 1e6 + 7;
const int MX = 1e9 + 7;
const LL INF = 1LL * MX * MX;

const int DX[] = {-1, -1, 1, 1};
const int DY[] = {-1, 1, -1, 1};

int n, m;
string input[N];
vector <int> pref[N];
vector <int> tmp_pref[N];

bool check(int r, int c, int T) {
	if(input[r][c] != 'X' || r < T + 1 || c < T + 1 || r + T > n || c + T > m)
		return false;
	return pref[r + T][c + T] - pref[r - T - 1][c + T] - pref[r + T][c - T - 1] + pref[r - T - 1][c - T - 1] == (2 * T + 1) * (2 * T + 1);
}

bool ask(int T) {
	for(int i = 0; i <= n; ++i) {
		tmp_pref[i].resize(m + 1);
		for(auto &c: tmp_pref[i])
			c = 0;
	}

	for(int i = 1; i <= n; ++i)
		for(int j = 1; j <= m; ++j)
			if(check(i, j, T)) {
				tmp_pref[i + T][j + T] += 1;
				tmp_pref[i - T - 1][j - T - 1] += 1;

				tmp_pref[i + T][j - T - 1] -= 1;
				tmp_pref[i - T - 1][j + T] -= 1;
			}

	for(int i = n; i >= 1; --i)
		for(int j = m; j >= 1; --j) {
			if(i < n) tmp_pref[i][j] += tmp_pref[i + 1][j];
			if(j < m) tmp_pref[i][j] += tmp_pref[i][j + 1];
			if(i < n && j < m)	tmp_pref[i][j] -= tmp_pref[i + 1][j + 1];
			if(tmp_pref[i][j] == 0 && input[i][j] == 'X')
				return false;
		}

	return true;
}

int solve() {
	int s = 0, e = min(n - 1, m - 1) / 2;
	while(s < e) {
		int mid = (s + e + 1) >> 1;
		if(ask(mid))
			s = mid;
		else
			e = mid - 1;
	}

	return s;
}

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);

	cin >> n >> m;
	for(int i = 1; i <= n; ++i) {
		cin >> input[i];
		input[i] = "." + input[i];
		pref[i].resize(m + 1);
	}

	pref[0].resize(m + 1);
	for(int i = 1; i <= n; ++i)
		for(int j = 1; j <= m; ++j)
			pref[i][j] = pref[i - 1][j] + pref[i][j - 1] - pref[i - 1][j - 1] + (input[i][j] == 'X');

	int T = solve();
	printf("%d\n", T);

	for(int i = 1; i <= n; ++i) {
		for(int j = 1; j <= m; ++j)
			printf(check(i, j, T) ? "X" : ".");
		puts("");
	}

	return 0;
}


#include <bits/stdc++.h>

using namespace std;

typedef long long int LL;

#define st first
#define nd second
#define PLL pair <LL, LL>
#define PII pair <int, int>

const int N = 1e6 + 7;
const int MX = 1e9 + 7;
const LL INF = 1LL * MX * MX;

int n, m;
string input[N];
vector <int> val[4][N];

bool check(int x, int y) {
	return x < 1 || y < 1 || x > n || y > m || input[x][y] == '.';
}

bool is_corner(const int &r, const int &c, const int &dx, const int &dy) {
	if(check(r + dx, c) && check(r, c + dy))
		return true;
	return !check(r + dx, c) && !check(r, c + dy) && check(r + dx, c + dy);
}

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);

	cin >> n >> m;

	const int FROMX[] = {1, 1, n, n};
	const int TOX[] = {n + 1, n + 1, 0, 0};

	const int FROMY[] = {1, m, 1, m};
	const int TOY[] = {m + 1, 0, m + 1, 0};

	const int DX[] = {-1, -1, 1, 1};
	const int DY[] = {-1, 1, -1, 1};

	for(int i = 1; i <= n; ++i) {
		cin >> input[i];
		input[i] = "." + input[i] + ".";
	}

	for(int t = 0; t < 4; ++t) {
		for(int i = 0; i <= n + 1; ++i)
			val[t][i].resize(m + 2, -1);

		for(int r = FROMX[t]; r != TOX[t]; r -= DX[t]) {
			for(int c = FROMY[t]; c != TOY[t]; c -= DY[t]) {
				if(input[r][c] == '.')	continue;
				val[t][r][c] = min(min(val[t][r + DX[t]][c], val[t][r][c + DY[t]]), val[t][r + DX[t]][c + DY[t]]) + 1;
			}
		}
	}

	int T = min(n - 1, m - 1) / 2;
	for(int t = 0; t < 4; ++t) {
		for(int r = FROMX[t]; r != TOX[t]; r -= DX[t]) {
			for(int c = FROMY[t]; c != TOY[t]; c -= DY[t]) {
				if(input[r][c] == '.')	continue;
				if(is_corner(r, c, -DX[t], -DY[t])){
//					printf("for %d -> %d %d %d\n", t, r, c, val[t][r][c]);
					T = min(T, val[t][r][c] / 2);
				}
			}
		}
	}

	printf("%d\n", T);
	for(int i = 1; i <= n; ++i) {
		for(int j = 1; j <= m; ++j){
			bool ok = input[i][j] == 'X';
			for(int t = 0; t < 4; ++t)
				ok &= val[t][i][j] >= T;

			if(ok)
				printf("X");
			else
				printf(".");
		}

		puts("");
	}

	return 0;
}


//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

// ここまで

fn run() {
    input! {
        h: usize,
        w: usize,
        s: [chars; h],
    }
    let mut cnt = vec![vec![0; w + 1]; h + 1];
    for i in (0..h).rev() {
        for j in (0..w).rev() {
            cnt[i][j] = cnt[i + 1][j] + cnt[i][j + 1] - cnt[i + 1][j + 1];
            if s[i][j] == 'X' {
                cnt[i][j] += 1;
            }
        }
    }
    let mut l = 0;
    let mut r = (std::cmp::min(h, w) - 1) / 2 + 1;
    while r - l > 1 {
        let m = (l + r) / 2;
        let mut a = vec![vec!['.'; w]; h];
        let mut q = std::collections::VecDeque::new();
        for i in m..(h - m) {
            for j in m..(w - m) {
                let x = i - m;
                let y = j - m;
                let z = i + m + 1;
                let w = j + m + 1;
                if cnt[x][y] - cnt[x][w] - cnt[z][y] + cnt[z][w] == (z - x) * (w - y) {
                    a[i][j] = 'X';
                    q.push_back((i, j, 0));
                }
            }
        }
        while let Some((i, j, d)) = q.pop_front() {
            if d == m {
                break;
            }
            for &(x, y) in [(i + 1, j), (i + 1, j + 1), (i, j + 1), (i - 1, j + 1), (i - 1, j), (i - 1, j - 1), (i, j - 1), (i + 1, j - 1)].iter() {
                if a[x][y] == '.' {
                    a[x][y] = 'X';
                    q.push_back((x, y, d + 1));
                }
            }
        }
        let mut ok = true;
        for i in 0..h {
            for j in 0..w {
                if s[i][j] != a[i][j] {
                    ok = false;
                }
            }
        }
        if ok {
            l = m;
        } else {
            r = m;
        }
    }
    let mut a = vec![vec!['.'; w]; h];
    let m = l;
    for i in m..(h - m) {
        for j in m..(w - m) {
            let x = i - m;
            let y = j - m;
            let z = i + m + 1;
            let w = j + m + 1;
            if cnt[x][y] - cnt[x][w] - cnt[z][y] + cnt[z][w] == (z - x) * (w - y) {
                a[i][j] = 'X';
            }
        }
    }
    let cnt = l;
    let mut ans = String::new();
    for i in 0..h {
        for j in 0..w {
            ans.push(a[i][j]);
        }
        ans.push('\n');
    }
    print!("{}\n{}", cnt, ans);
}

fn main() {
    run();
}


//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

// ここまで

fn run() {
    input! {
        h: usize,
        w: usize,
        s: [chars; h],
    }
    let mut s = s;
    let mut a = vec![];
    a.push(vec!['.'; w + 2]);
    while let Some(mut b) = s.pop() {
        b.push('.');
        b.reverse();
        b.push('.');
        b.reverse();
        a.push(b);
    }
    a.push(vec!['.'; w + 2]);
    a.reverse();
    let mut ans = h;
    for i in 1..=h {
        for j in 1..=w {
            if a[i][j] == 'X' && a[i][j - 1] != 'X' {
                let mut cnt = 1;
                while a[i][j + cnt] == 'X' {
                    cnt += 1;
                }
                ans = std::cmp::min(ans, (cnt - 1) / 2);
            }
        }
    }
    for j in 1..=w {
        for i in 1..=h {
            if a[i][j] == 'X' && a[i - 1][j] != 'X' {
                let mut cnt = 1;
                while a[i + cnt][j] == 'X' {
                    cnt += 1;
                }
                ans = std::cmp::min(ans, (cnt - 1) / 2);
            }
        }
    }
    let mut now = std::collections::BTreeSet::new();
    for i in 1..=h {
        for j in 1..=w {
            if a[i][j] == '.' {
                continue;
            }
            for &(x, y) in [(i + 1, j), (i + 1, j + 1), (i, j + 1), (i - 1, j + 1), (i - 1, j), (i - 1, j - 1), (i, j - 1), (i + 1, j - 1)].iter() {
                if a[x][y] == '.' {
                    now.insert((i, j));
                }
            }
        }
    }
    for _ in 0..ans {
        let mut next = std::collections::BTreeSet::new();
        for &(i, j) in now.iter() {
            a[i][j] = '.';
            for &(x, y) in [(i + 1, j), (i + 1, j + 1), (i, j + 1), (i - 1, j + 1), (i - 1, j), (i - 1, j - 1), (i, j - 1), (i + 1, j - 1)].iter() {
                if a[x][y] == 'X' {
                    next.insert((x, y));
                }
            }
        }
        now = next;
    }
    let cnt = ans;
    let mut ans = String::new();
    for i in 1..=h {
        for j in 1..=w {
            ans.push(a[i][j]);
        }
        ans.push('\n');
    }
    print!("{}\n{}", cnt, ans);
}

fn main() {
    run();
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) throws Exception {
        Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27);
        thread.start();
        thread.join();
    }

    static class TaskAdapter implements Runnable {
        @Override
        public void run() {
            InputStream inputStream = System.in;
            OutputStream outputStream = System.out;
            FastInput in = new FastInput(inputStream);
            FastOutput out = new FastOutput(outputStream);
            TaskC solver = new TaskC();
            solver.solve(1, in, out);
            out.close();
        }
    }

    static class TaskC {
        LongDeque deque = new LongDeque(1000000);
        int[][] buf;
        int[][] time;
        boolean[][] border;
        int[][] mat;

        public void solve(int testNumber, FastInput in, FastOutput out) {
            int n = in.readInt();
            int m = in.readInt();
            mat = new int[n][m];
            buf = new int[n][m];
            time = new int[n][m];
            border = new boolean[n][m];
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    mat[i][j] = in.readChar() == 'X' ? 1 : 0;
                }
            }
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    if (mat[i][j] == 0) {
                        continue;
                    }
                    if (i == 0 || i == n - 1 || j == 0 || j == m - 1) {
                        border[i][j] = true;
                        continue;
                    }
                    int cnt = 0;
                    for (int dx = -1; dx <= 1; dx++) {
                        for (int dy = -1; dy <= 1; dy++) {
                            int mi = i + dx;
                            int mj = j + dy;
                            cnt += mat[mi][mj];
                        }
                    }

                    if (cnt != 9) {
                        border[i][j] = true;
                    }
                }
            }

            int l = 0;
            int r = Math.min(n / 2, m / 2);
            while (l < r) {
                int mid = (l + r + 1) >>> 1;
                if (check(mid)) {
                    l = mid;
                } else {
                    r = mid - 1;
                }
            }

            check(l);
            out.println(l);
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    out.append(time[i][j] == 0 ? 'X' : '.');
                }
                out.println();
            }
        }

        public boolean check(int t) {
            int n = mat.length;
            int m = mat[0].length;
            SequenceUtils.deepFill(time, -1);
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    if (!border[i][j]) {
                        continue;
                    }
                    deque.addLast(DigitUtils.asLong(i, j));
                    time[i][j] = 0;
                }
            }
            while (!deque.isEmpty()) {
                long head = deque.removeFirst();
                int x = DigitUtils.highBit(head);
                int y = DigitUtils.lowBit(head);
                for (int dx = -1; dx <= 1; dx++) {
                    for (int dy = -1; dy <= 1; dy++) {
                        int mx = x + dx;
                        int my = y + dy;
                        if (mx < 0 || mx >= n || my < 0 || my >= m || mat[mx][my] == 0 ||
                                time[mx][my] != -1) {
                            continue;
                        }
                        time[mx][my] = time[x][y] + 1;
                        deque.addLast(DigitUtils.asLong(mx, my));
                    }
                }
            }

            SequenceUtils.deepFill(buf, 0);
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    if (time[i][j] >= t) {
                        deque.addLast(DigitUtils.asLong(i, j));
                        time[i][j] = 0;
                    } else {
                        time[i][j] = -1;
                    }
                }
            }

            while (!deque.isEmpty()) {
                long head = deque.removeFirst();
                int x = DigitUtils.highBit(head);
                int y = DigitUtils.lowBit(head);
                buf[x][y] = 1;
                if (time[x][y] >= t) {
                    continue;
                }
                for (int dx = -1; dx <= 1; dx++) {
                    for (int dy = -1; dy <= 1; dy++) {
                        int mx = x + dx;
                        int my = y + dy;
                        if (time[mx][my] != -1) {
                            continue;
                        }
                        if (mx < 0 || mx >= n || my < 0 || my >= m || mat[mx][my] == 0) {
                            return false;
                        }
                        time[mx][my] = time[x][y] + 1;
                        deque.addLast(DigitUtils.asLong(mx, my));
                    }
                }
            }

            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    if (buf[i][j] != mat[i][j]) {
                        return false;
                    }
                }
            }
            return true;
        }

    }

    static class FastInput {
        private final InputStream is;
        private byte[] buf = new byte[1 << 13];
        private int bufLen;
        private int bufOffset;
        private int next;

        public FastInput(InputStream is) {
            this.is = is;
        }

        private int read() {
            while (bufLen == bufOffset) {
                bufOffset = 0;
                try {
                    bufLen = is.read(buf);
                } catch (IOException e) {
                    bufLen = -1;
                }
                if (bufLen == -1) {
                    return -1;
                }
            }
            return buf[bufOffset++];
        }

        public void skipBlank() {
            while (next >= 0 && next <= 32) {
                next = read();
            }
        }

        public int readInt() {
            int sign = 1;

            skipBlank();
            if (next == '+' || next == '-') {
                sign = next == '+' ? 1 : -1;
                next = read();
            }

            int val = 0;
            if (sign == 1) {
                while (next >= '0' && next <= '9') {
                    val = val * 10 + next - '0';
                    next = read();
                }
            } else {
                while (next >= '0' && next <= '9') {
                    val = val * 10 - next + '0';
                    next = read();
                }
            }

            return val;
        }

        public char readChar() {
            skipBlank();
            char c = (char) next;
            next = read();
            return c;
        }

    }

    static class LongDeque {
        long[] data;
        int bpos;
        int epos;
        int cap;

        public LongDeque(int cap) {
            this.cap = cap + 1;
            this.data = new long[this.cap];
        }

        public boolean isEmpty() {
            return epos == bpos;
        }

        private int next(int i) {
            int n = i + 1;
            return n == cap ? 0 : n;
        }

        public long removeFirst() {
            int t = bpos;
            bpos = next(bpos);
            return data[t];
        }

        public void addLast(long val) {
            data[epos] = val;
            epos = next(epos);
        }

        public String toString() {
            StringBuilder builder = new StringBuilder();
            for (int i = bpos; i != epos; i = next(i)) {
                builder.append(data[i]).append(' ');
            }
            return builder.toString();
        }

    }

    static class SequenceUtils {
        public static void deepFill(Object array, int val) {
            if (!array.getClass().isArray()) {
                throw new IllegalArgumentException();
            }
            if (array instanceof int[]) {
                int[] intArray = (int[]) array;
                Arrays.fill(intArray, val);
            } else {
                Object[] objArray = (Object[]) array;
                for (Object obj : objArray) {
                    deepFill(obj, val);
                }
            }
        }

    }

    static class DigitUtils {
        private DigitUtils() {
        }

        public static long asLong(int high, int low) {
            return (((long) high) << 32) | low;
        }

        public static int highBit(long x) {
            return (int) (x >> 32);
        }

        public static int lowBit(long x) {
            return (int) x;
        }

    }

    static class FastOutput implements AutoCloseable, Closeable {
        private StringBuilder cache = new StringBuilder(10 << 20);
        private final Writer os;

        public FastOutput(Writer os) {
            this.os = os;
        }

        public FastOutput(OutputStream os) {
            this(new OutputStreamWriter(os));
        }

        public FastOutput append(char c) {
            cache.append(c);
            return this;
        }

        public FastOutput println(int c) {
            cache.append(c).append('\n');
            return this;
        }

        public FastOutput println() {
            cache.append('\n');
            return this;
        }

        public FastOutput flush() {
            try {
                os.append(cache);
                os.flush();
                cache.setLength(0);
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
            return this;
        }

        public void close() {
            flush();
            try {
                os.close();
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }

        public String toString() {
            return cache.toString();
        }

    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) throws Exception {
        Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27);
        thread.start();
        thread.join();
    }

    static class TaskAdapter implements Runnable {
        @Override
        public void run() {
            InputStream inputStream = System.in;
            OutputStream outputStream = System.out;
            FastInput in = new FastInput(inputStream);
            FastOutput out = new FastOutput(outputStream);
            TaskC solver = new TaskC();
            solver.solve(1, in, out);
            out.close();
        }
    }

    static class TaskC {
        IntDequeBeta dequeX = new IntDequeBeta(1000000);
        IntDequeBeta dequeY = new IntDequeBeta(1000000);
        int[][] buf;
        int[][] time;
        boolean[][] border;
        int[][] mat;

        public void solve(int testNumber, FastInput in, FastOutput out) {
            int n = in.readInt();
            int m = in.readInt();
            mat = new int[n][m];
            buf = new int[n][m];
            time = new int[n][m];
            border = new boolean[n][m];
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    mat[i][j] = in.readChar() == 'X' ? 1 : 0;
                }
            }
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    if (mat[i][j] == 0) {
                        continue;
                    }
                    if (i == 0 || i == n - 1 || j == 0 || j == m - 1) {
                        border[i][j] = true;
                        continue;
                    }
                    int cnt = 0;
                    for (int dx = -1; dx <= 1; dx++) {
                        for (int dy = -1; dy <= 1; dy++) {
                            int mi = i + dx;
                            int mj = j + dy;
                            cnt += mat[mi][mj];
                        }
                    }

                    if (cnt != 9) {
                        border[i][j] = true;
                    }
                }
            }

            int l = 0;
            int r = 1000000;
            while (l < r) {
                int mid = (l + r + 1) >>> 1;
                if (check(mid)) {
                    l = mid;
                } else {
                    r = mid - 1;
                }
            }

            check(l);
            out.println(l);
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    out.append(time[i][j] == 0 ? 'X' : '.');
                }
                out.println();
            }
        }

        public boolean check(int t) {
            int n = mat.length;
            int m = mat[0].length;
            SequenceUtils.deepFill(time, -1);
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    if (!border[i][j]) {
                        continue;
                    }
                    dequeX.addLast(i);
                    dequeY.addLast(j);
                    time[i][j] = 0;
                }
            }
            while (!dequeX.isEmpty()) {
                int x = dequeX.removeFirst();
                int y = dequeY.removeFirst();
                for (int dx = -1; dx <= 1; dx++) {
                    for (int dy = -1; dy <= 1; dy++) {
                        int mx = x + dx;
                        int my = y + dy;
                        if (mx < 0 || mx >= n || my < 0 || my >= m || mat[mx][my] == 0 ||
                                time[mx][my] != -1) {
                            continue;
                        }
                        time[mx][my] = time[x][y] + 1;
                        dequeX.addLast(mx);
                        dequeY.addLast(my);
                    }
                }
            }

            SequenceUtils.deepFill(buf, 0);
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    if (time[i][j] >= t) {
                        dequeX.addLast(i);
                        dequeY.addLast(j);
                        time[i][j] = 0;
                    } else {
                        time[i][j] = -1;
                    }
                }
            }

            while (!dequeX.isEmpty()) {
                int x = dequeX.removeFirst();
                int y = dequeY.removeFirst();
                buf[x][y] = 1;
                if (time[x][y] >= t) {
                    continue;
                }
                for (int dx = -1; dx <= 1; dx++) {
                    for (int dy = -1; dy <= 1; dy++) {
                        int mx = x + dx;
                        int my = y + dy;
                        if (mx < 0 || mx >= n || my < 0 || my >= m || mat[mx][my] == 0) {
                            return false;
                        }
                        if (time[mx][my] != -1) {
                            continue;
                        }
                        time[mx][my] = time[x][y] + 1;
                        dequeX.addLast(mx);
                        dequeY.addLast(my);
                    }
                }
            }

            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    if (buf[i][j] != mat[i][j]) {
                        return false;
                    }
                }
            }
            return true;
        }

    }

    static class FastInput {
        private final InputStream is;
        private byte[] buf = new byte[1 << 13];
        private int bufLen;
        private int bufOffset;
        private int next;

        public FastInput(InputStream is) {
            this.is = is;
        }

        private int read() {
            while (bufLen == bufOffset) {
                bufOffset = 0;
                try {
                    bufLen = is.read(buf);
                } catch (IOException e) {
                    bufLen = -1;
                }
                if (bufLen == -1) {
                    return -1;
                }
            }
            return buf[bufOffset++];
        }

        public void skipBlank() {
            while (next >= 0 && next <= 32) {
                next = read();
            }
        }

        public int readInt() {
            int sign = 1;

            skipBlank();
            if (next == '+' || next == '-') {
                sign = next == '+' ? 1 : -1;
                next = read();
            }

            int val = 0;
            if (sign == 1) {
                while (next >= '0' && next <= '9') {
                    val = val * 10 + next - '0';
                    next = read();
                }
            } else {
                while (next >= '0' && next <= '9') {
                    val = val * 10 - next + '0';
                    next = read();
                }
            }

            return val;
        }

        public char readChar() {
            skipBlank();
            char c = (char) next;
            next = read();
            return c;
        }

    }

    static class SequenceUtils {
        public static void deepFill(Object array, int val) {
            if (!array.getClass().isArray()) {
                throw new IllegalArgumentException();
            }
            if (array instanceof int[]) {
                int[] intArray = (int[]) array;
                Arrays.fill(intArray, val);
            } else {
                Object[] objArray = (Object[]) array;
                for (Object obj : objArray) {
                    deepFill(obj, val);
                }
            }
        }

    }

    static class FastOutput implements AutoCloseable, Closeable {
        private StringBuilder cache = new StringBuilder(10 << 20);
        private final Writer os;

        public FastOutput(Writer os) {
            this.os = os;
        }

        public FastOutput(OutputStream os) {
            this(new OutputStreamWriter(os));
        }

        public FastOutput append(char c) {
            cache.append(c);
            return this;
        }

        public FastOutput println(int c) {
            cache.append(c).append('\n');
            return this;
        }

        public FastOutput println() {
            cache.append('\n');
            return this;
        }

        public FastOutput flush() {
            try {
                os.append(cache);
                os.flush();
                cache.setLength(0);
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
            return this;
        }

        public void close() {
            flush();
            try {
                os.close();
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }

        public String toString() {
            return cache.toString();
        }

    }

    static interface IntIterator {
        boolean hasNext();

        int next();

    }

    static class IntDequeBeta {
        private int[] data;
        private int bpos;
        private int epos;
        private static final int[] EMPTY = new int[0];
        private int n;

        public IntDequeBeta(int cap) {
            if (cap == 0) {
                data = EMPTY;
            } else {
                data = new int[cap];
            }
            bpos = 0;
            epos = 0;
            n = cap;
        }

        private void expandSpace(int len) {
            while (n < len) {
                n = Math.max(n + 10, n * 2);
            }
            int[] newData = new int[n];
            if (bpos <= epos) {
                if (bpos < epos) {
                    System.arraycopy(data, bpos, newData, 0, epos - bpos);
                }
            } else {
                System.arraycopy(data, bpos, newData, 0, data.length - bpos);
                System.arraycopy(data, 0, newData, data.length - bpos, epos);
            }
            epos = size();
            bpos = 0;
            data = newData;
        }

        public IntIterator iterator() {
            return new IntIterator() {
                int index = bpos;

                public boolean hasNext() {
                    return index != epos;
                }

                public int next() {
                    int ans = data[index];
                    index = IntDequeBeta.this.next(index);
                    return ans;
                }
            };
        }

        public int removeFirst() {
            int ans = data[bpos];
            bpos = next(bpos);
            return ans;
        }

        public void addLast(int x) {
            ensureMore();
            data[epos] = x;
            epos = next(epos);
        }

        private int next(int x) {
            return x + 1 >= n ? 0 : x + 1;
        }

        private void ensureMore() {
            if (next(epos) == bpos) {
                expandSpace(n + 1);
            }
        }

        public int size() {
            int ans = epos - bpos;
            if (ans < 0) {
                ans += data.length;
            }
            return ans;
        }

        public boolean isEmpty() {
            return bpos == epos;
        }

        public String toString() {
            StringBuilder builder = new StringBuilder();
            for (IntIterator iterator = iterator(); iterator.hasNext(); ) {
                builder.append(iterator.next()).append(' ');
            }
            return builder.toString();
        }

    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskC {
        int[][] map;
        int[][] cum;
        int N;
        int M;

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            N = in.nextInt();
            M = in.nextInt();
            map = new int[N + 1][M + 1];
            cum = new int[N + 1][M + 1];
            for (int i = 1; i <= N; i++) {
                char[] s = in.next().toCharArray();
                for (int j = 1; j <= M; j++) {
                    map[i][j] = (s[j - 1] == 'X' ? 1 : 0);
                    cum[i][j] = cum[i - 1][j] + cum[i][j - 1] - cum[i - 1][j - 1] + map[i][j];
                }
            }
            int low = 0;
            int high = (Math.min(N, M) + 1) / 2;
            while (low < high) {
                int mid = (low + high + 1) >> 1;
                if (works(mid)) {
                    low = mid;
                } else {
                    high = mid - 1;
                }
            }
            print(low, out);
        }

        boolean works(int T) {
            int size = T * 2 + 1;
            int[][] squares = new int[N + 2][M + 2];
            for (int i = size; i <= N; i++) {
                for (int j = size; j <= M; j++) {
                    if (cum[i][j] - cum[i - size][j] - cum[i][j - size] + cum[i - size][j - size] == size * size) {
                        squares[i + 1][j + 1]++;
                        squares[i - size + 1][j - size + 1]++;
                        squares[i - size + 1][j + 1]--;
                        squares[i + 1][j - size + 1]--;
                    }
                }
            }
            for (int i = 1; i <= N; i++) {
                for (int j = 1; j <= M; j++) {
                    squares[i][j] += squares[i - 1][j] + squares[i][j - 1] - squares[i - 1][j - 1];
                    if ((squares[i][j] > 0 && map[i][j] == 0) || (squares[i][j] == 0 && map[i][j] == 1)) {
                        return false;
                    }
                }
            }
            return true;
        }

        void print(int T, PrintWriter out) {
            int size = T * 2 + 1;
            out.println(T);
            int[][] squares = new int[N + 1][M + 1];
            for (int i = size; i <= N; i++) {
                for (int j = size; j <= M; j++) {
                    if (cum[i][j] - cum[i - size][j] - cum[i][j - size] + cum[i - size][j - size] == size * size) {
                        squares[i - T][j - T] = 1;
                    }
                }
            }
            for (int i = 1; i <= N; i++) {
                for (int j = 1; j <= M; j++) {
                    if (squares[i][j] == 1) {
                        out.print("X");
                    } else {
                        out.print(".");
                    }
                }
                out.println();
            }
        }

    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskC {
        int[][] map;
        int[][] cum;
        int N;
        int M;

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            N = in.nextInt();
            M = in.nextInt();
            map = new int[N + 1][M + 1];
            cum = new int[N + 1][M + 1];
            for (int i = 1; i <= N; i++) {
                char[] s = in.next().toCharArray();
                for (int j = 1; j <= M; j++) {
                    map[i][j] = (s[j - 1] == 'X' ? 1 : 0);
                    cum[i][j] = cum[i - 1][j] + cum[i][j - 1] - cum[i - 1][j - 1] + map[i][j];
                }
            }
            int low = 0;
            int high = (Math.min(N, M) + 1) / 2;
            while (low < high) {
                int mid = (low + high + 1) >> 1;
                if (works(mid)) {
                    low = mid;
                } else {
                    high = mid - 1;
                }
            }
            print(low, out);
        }

        boolean works(int T) {
            int size = T * 2 + 1;
            int[][] squares = new int[N + 2][M + 2];
            for (int i = size; i <= N; i++) {
                for (int j = size; j <= M; j++) {
                    if (cum[i][j] - cum[i - size][j] - cum[i][j - size] + cum[i - size][j - size] == size * size) {
                        squares[i + 1][j + 1]++;
                        squares[i - size + 1][j - size + 1]++;
                        squares[i - size + 1][j + 1]--;
                        squares[i + 1][j - size + 1]--;
                    }
                }
            }
            for (int i = 1; i <= N; i++) {
                for (int j = 1; j <= M; j++) {
                    squares[i][j] += squares[i - 1][j] + squares[i][j - 1] + squares[i - 1][j - 1];
                    if (squares[i][j] == 0 && map[i][j] == 1) {
                        return false;
                    }
                }
            }
            return true;
        }

        void print(int T, PrintWriter out) {
            int size = T * 2 + 1;
            out.println(T);
            int[][] squares = new int[N + 1][M + 1];
            for (int i = size; i <= N; i++) {
                for (int j = size; j <= M; j++) {
                    if (cum[i][j] - cum[i - size][j] - cum[i][j - size] + cum[i - size][j - size] == size * size) {
                        squares[i - T][j - T] = 1;
                    }
                }
            }
            for (int i = 1; i <= N; i++) {
                for (int j = 1; j <= M; j++) {
                    if (squares[i][j] == 1) {
                        out.print("X");
                    } else {
                        out.print(".");
                    }
                }
                out.println();
            }
        }

    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskC {
        int[][] map;
        int[][] cum;
        int N;
        int M;

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            N = in.nextInt();
            M = in.nextInt();
            map = new int[N + 1][M + 1];
            cum = new int[N + 1][M + 1];
            for (int i = 1; i <= N; i++) {
                char[] s = in.next().toCharArray();
                for (int j = 1; j <= M; j++) {
                    map[i][j] = (s[j - 1] == 'X' ? 1 : 0);
                    cum[i][j] = cum[i - 1][j] + cum[i][j - 1] - cum[i - 1][j - 1] + map[i][j];
                }
            }
            int low = 0;
            int high = (Math.min(N, M) + 1) / 2;
            while (low < high) {
                int mid = (low + high + 1) >> 1;
                if (works(mid)) {
                    low = mid;
                } else {
                    high = mid - 1;
                }
            }
            print(low, out);
        }

        boolean works(int T) {
            int size = T * 2 + 1;
            int[][] squares = new int[N + 2][M + 2];
            for (int i = size; i <= N; i++) {
                for (int j = size; j <= M; j++) {
                    if (cum[i][j] - cum[i - size][j] - cum[i][j - size] + cum[i - size][j - size] == size * size) {
                        squares[i + 1][j + 1]++;
                        squares[i - size + 1][j - size + 1]++;
                        squares[i - size + 1][j + 1]--;
                        squares[i + 1][j - size + 1]--;
                    }
                }
            }
            for (int i = 1; i <= N; i++) {
                for (int j = 1; j <= M; j++) {
                    squares[i][j] += squares[i - 1][j] + squares[i][j - 1] + squares[i - 1][j - 1];
                    if ((squares[i][j] > 0 && map[i][j] == 0) || (squares[i][j] == 0 && map[i][j] == 1)) {
                        return false;
                    }
                }
            }
            return true;
        }

        void print(int T, PrintWriter out) {
            int size = T * 2 + 1;
            out.println(T);
            int[][] squares = new int[N + 1][M + 1];
            for (int i = size; i <= N; i++) {
                for (int j = size; j <= M; j++) {
                    if (cum[i][j] - cum[i - size][j] - cum[i][j - size] + cum[i - size][j - size] == size * size) {
                        squares[i - T][j - T] = 1;
                    }
                }
            }
            for (int i = 1; i <= N; i++) {
                for (int j = 1; j <= M; j++) {
                    if (squares[i][j] == 1) {
                        out.print("X");
                    } else {
                        out.print(".");
                    }
                }
                out.println();
            }
        }

    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;

/*
12 10
.XXXXXX...
.XXXXXX...
.XXXXXX...
.XXXXXX...
.XXXXXXX..
..........
...XXXXXX.
...XXXXXX.
...XXXXXX.
...XXXXXX.
...XXXXXX.
..........

12 12
.XXXXXX.....
.XXXXXX.....
.XXXXXXXXX..
.XXXXXXXXX..
.XXXXXXXXX..
............
...XXXXXX...
...XXXXXX...
...XXXXXX...
...XXXXXX...
...XXXXXX...
............

13 12
.XXXXXX.....
.XXXXXXXXXX.
.XXXXXXXXXX.
.XXXXXXXXXX.
.XXXXXXXXXX.
....XXXXXXX.
............
...XXXXXX...
...XXXXXX...
...XXXXXX...
...XXXXXX...
...XXXXXX...
............

 */
public class C2 {
	static PrintWriter out = new PrintWriter(System.out);

	static int R,C;
	static char b[][];
	static int box[][];
	static int dr[] = new int[] {-1,-1,-1,0,0,1,1,1};
	static int dc[] = new int[] {-1,0,1,-1,1,0,1,-1};
	static final boolean debug = false;
	public static void main(String[] args) {
		FS in = new FS();
		R = in.nextInt();
		C = in.nextInt();
		b = new char[R+2][C+2];
		for(char a[] : b) Arrays.fill(a, '.');

		for(int i = 1; i <= R; i++) {
			char c[] = in.next().toCharArray();
			for(int j = 1; j <= C; j++) {
				b[i][j] = c[j-1];
			}
		}
		R += 2;
		C += 2;
		box = new int[R][C];
		for(int a[] : box) Arrays.fill(a, -1);
		int max = -1;

		ArrayDeque<Pair> q = new ArrayDeque<Pair>();
		for(int i = 0; i < R; i++)
			for(int j = 0; j < C; j++)
				if(b[i][j] == '.') {q.add(new Pair(i,j)); box[i][j] = 0;}
		while(!q.isEmpty()) {
			Pair p = q.poll();
			max = Math.max(max, box[p.r][p.c]);
			for(int k = 0; k < dr.length; k++) {
				int nr = p.r+dr[k];
				int nc = p.c+dc[k];
				if(!valid(nr,nc) || box[nr][nc] != -1) continue;
				box[nr][nc] = box[p.r][p.c]+1;
				q.add(new Pair(nr,nc));
			}
		}

		int lo = 0, hi = max;
		int best = -1;
		while(lo <= hi) {
			int mid = (lo+hi)/2;
			if(works(mid)) {
				best = Math.max(best, mid);
				lo = mid+1;
			}
			else hi = mid-1;
		}

		if(debug) {
			for(int i = 0; i < R; i++) {
				for(int j = 0; j < C; j++) {
					System.out.print(box[i][j]);
				}System.out.println();
			}
		}

		out.println(best);
		for(int i = 1; i < R-1; i++) {
			for(int j = 1; j < C-1; j++) {
				if(box[i][j] > best) out.print('X');
				else out.print('.');
			}out.println();
		}
		out.close();
	}

	static boolean works(int t) {
		if(debug) System.out.println("T: "+t);
		ArrayDeque<Pair> q = new ArrayDeque<Pair>();
		boolean vis[][] = new boolean[R][C];
		for(int i = 0; i < R; i++) {
			for(int j = 0; j < C; j++) {
				if(box[i][j]-1 >= t) {
					q.add(new Pair(i,j));
					vis[i][j] = true;
				}
			}
		}

		for(int iter = 0; iter < t; iter++) {
			ArrayDeque<Pair> q2 = new ArrayDeque<Pair>();
			while(!q.isEmpty()) {
				Pair p = q.poll();
				for(int k = 0; k < dr.length; k++) {
					int nr = p.r+dr[k];
					int nc = p.c+dc[k];
					if(!valid(nr,nc) || b[nr][nc] == '.') return false;
					if(vis[nr][nc]) continue;
					vis[nr][nc] = true;
					q2.add(new Pair(nr,nc));
				}
			}
			q = q2;
		}

		for(int i = 0; i < R; i++) {
			for(int j = 0; j < C; j++) {
				if(b[i][j] == 'X' && !vis[i][j]) return false;
			}
		}

		if(debug) System.out.println("   true!");
		return true;
	}

	static class Pair{
		int r,c;
		public Pair(int rr, int cc) {
			r=rr;
			c=cc;
		}
		@Override
		public String toString() {
			return "("+r+","+c+")";
		}
	}

	static boolean valid(int r, int c) {
		return r >= 0 && r < R && c >= 0 && c < C;
	}

	static class FS{
		BufferedReader br;
		StringTokenizer st;
		public FS() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}
		String next() {
			while(st == null || !st.hasMoreElements()) {
				try {st = new StringTokenizer(br.readLine());}
				catch(Exception e) { throw null;}
			}
			return st.nextToken();
		}
		int nextInt() { return Integer.parseInt(next());}
		double nextDouble() { return Double.parseDouble(next());}
		long nextLong() { return Long.parseLong(next());}
		int[] NIA(int n) {
			int r[] = new int[n];
			for(int i = 0; i < n; i++) r[i] = nextInt();
			return r;
		}
		long[] NLA(int n) {
			long r[] = new long[n];
			for(int i = 0; i < n; i++) r[i] = nextLong();
			return r;
		}
		char[][] grid(int r, int c){
			char res[][] = new char[r][c];
			for(int i = 0; i < r; i++) {
				char l[] = next().toCharArray();
				for(int j = 0; j < c; j++) {
					res[i][j] = l[j];
				}
			}
			return res;
		}
	}

}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;

/*
12 10
.XXXXXX...
.XXXXXX...
.XXXXXX...
.XXXXXX...
.XXXXXXX..
..........
...XXXXXX.
...XXXXXX.
...XXXXXX.
...XXXXXX.
...XXXXXX.
..........

12 12
.XXXXXX.....
.XXXXXX.....
.XXXXXXXXX..
.XXXXXXXXX..
.XXXXXXXXX..
............
...XXXXXX...
...XXXXXX...
...XXXXXX...
...XXXXXX...
...XXXXXX...
............

13 12
.XXXXXX.....
.XXXXXXXXXX.
.XXXXXXXXXX.
.XXXXXXXXXX.
.XXXXXXXXXX.
....XXXXXXX.
............
...XXXXXX...
...XXXXXX...
...XXXXXX...
...XXXXXX...
...XXXXXX...
............

 */
public class C2 {
	static PrintWriter out = new PrintWriter(System.out);

	static int R,C;
	static char b[][];
	static int box[][];
	static int dr[] = new int[] {-1,-1,-1,0,0,1,1,1};
	static int dc[] = new int[] {-1,0,1,-1,1,0,1,-1};
	static final boolean debug = false;
	public static void main(String[] args) {
		FS in = new FS();
		R = in.nextInt();
		C = in.nextInt();
		b = new char[R+2][C+2];
		for(char a[] : b) Arrays.fill(a, '.');

		for(int i = 1; i <= R; i++) {
			char c[] = in.next().toCharArray();
			for(int j = 1; j <= C; j++) {
				b[i][j] = c[j-1];
			}
		}
		R += 2;
		C += 2;
		box = new int[R][C];
		for(int a[] : box) Arrays.fill(a, -1);
		int max = -1;

		ArrayDeque<Pair> q = new ArrayDeque<Pair>();
		for(int i = 0; i < R; i++)
			for(int j = 0; j < C; j++)
				if(b[i][j] == '.') {q.add(new Pair(i,j)); box[i][j] = 0;}
		while(!q.isEmpty()) {
			Pair p = q.poll();
			max = Math.max(max, box[p.r][p.c]);
			for(int k = 0; k < dr.length; k++) {
				int nr = p.r+dr[k];
				int nc = p.c+dc[k];
				if(!valid(nr,nc) || box[nr][nc] != -1) continue;
				box[nr][nc] = box[p.r][p.c]+1;
				q.add(new Pair(nr,nc));
			}
		}

		ArrayList<Pair> here[] = new ArrayList[max+1];
		for(int i = 0; i <= max; i++) here[i] = new ArrayList<Pair>();
		for(int i = 0; i < R; i++)
			for(int j = 0; j < C; j++)
				if(b[i][j] == 'X') here[box[i][j]].add(new Pair(i,j));

		if(debug) {
			for(int i = 0; i < R; i++) {
				for(int j = 0; j < C; j++) {
					System.out.print(box[i][j]);
				}System.out.println();
			}
		}

		int maxPrint = 1;
		q.clear();
		boolean vis[][] = new boolean[R][C];
		boolean done[][] = new boolean[R][C];
		boolean kill[][] = new boolean[R][C];
		for(Pair p : here[max]) { q.add(p); vis[p.r][p.c] = true;}

		maxPrint = max;
		int curIter = max;
		while(!q.isEmpty()) {
			ArrayDeque<Pair> q2 = new ArrayDeque<Pair>();
			while(!q.isEmpty()) {
				Pair p = q.poll();
				if(curIter == 0) maxPrint = 1;
				if(debug) System.out.println(curIter+" p= "+p+" toQ: "+(p.r >= R));
				boolean toQ = p.r >= R;
				if(toQ) p.r -= R;
				done[p.r][p.c] = true;

				for(int k = 0; k < dr.length; k++) {
					int nr = p.r+dr[k];
					int nc = p.c+dc[k];
					if(!valid(nr,nc) || b[nr][nc] == '.') continue;
					if(vis[nr][nc] && !toQ) continue;
					if(toQ && done[nr][nc]) continue;

					vis[nr][nc] = true;
					if(box[nr][nc] > curIter) {
						maxPrint = Math.min(maxPrint, box[nr][nc]);
						q.add(new Pair(nr+R,nc));
					}
					else {
						if(toQ) {
							q.add(new Pair(nr,nc));
							kill[nr][nc] = true;
						}
						else q2.add(new Pair(nr, nc));
					}
				}
			}
			curIter--;
			while(!q2.isEmpty()) {
				Pair p = q2.poll();
				if(!kill[p.r][p.c]) q.add(p);
				else kill[p.r][p.c] = false;
			}
		}

		for(Pair p : here[1]) {
			if(!vis[p.r][p.c]) maxPrint = 1;
		}

		out.println((maxPrint-1));
		for(int i = 1; i < R-1; i++) {
			for(int j = 1; j < C-1; j++) {
				if(box[i][j] >= maxPrint) out.print('X');
				else out.print('.');
			}out.println();
		}
		out.close();
	}

	static class Pair{
		int r,c;
		public Pair(int rr, int cc) {
			r=rr;
			c=cc;
		}
		@Override
		public String toString() {
			return "("+r+","+c+")";
		}
	}

	static boolean valid(int r, int c) {
		return r >= 0 && r < R && c >= 0 && c < C;
	}

	static class FS{
		BufferedReader br;
		StringTokenizer st;
		public FS() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}
		String next() {
			while(st == null || !st.hasMoreElements()) {
				try {st = new StringTokenizer(br.readLine());}
				catch(Exception e) { throw null;}
			}
			return st.nextToken();
		}
		int nextInt() { return Integer.parseInt(next());}
		double nextDouble() { return Double.parseDouble(next());}
		long nextLong() { return Long.parseLong(next());}
		int[] NIA(int n) {
			int r[] = new int[n];
			for(int i = 0; i < n; i++) r[i] = nextInt();
			return r;
		}
		long[] NLA(int n) {
			long r[] = new long[n];
			for(int i = 0; i < n; i++) r[i] = nextLong();
			return r;
		}
		char[][] grid(int r, int c){
			char res[][] = new char[r][c];
			for(int i = 0; i < r; i++) {
				char l[] = next().toCharArray();
				for(int j = 0; j < c; j++) {
					res[i][j] = l[j];
				}
			}
			return res;
		}
	}

}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.StringTokenizer;

public class C {
	static PrintWriter out = new PrintWriter(System.out);

	static int R,C;
	static char b[][];
	static int box[][];
	static int dr[] = new int[] {-1,-1,-1,0,0,1,1,1};
	static int dc[] = new int[] {-1,0,1,-1,1,0,1,-1};
	public static void main(String[] args) {
		FS in = new FS();
		R = in.nextInt();
		C = in.nextInt();
		b = new char[R+2][C+2];
		for(char a[] : b) Arrays.fill(a, '.');

		for(int i = 1; i <= R; i++) {
			char c[] = in.next().toCharArray();
			for(int j = 1; j <= C; j++) {
				b[i][j] = c[j-1];
			}
		}
		R += 2;
		C += 2;

		DisjointSet dsu = new DisjointSet(R*C);
		for(int i = 0; i < R; i++) {
			for(int j = 0; j < C; j++) {
				for(int k = 0; k < dr.length; k++) {
					int nr = i+dr[k];
					int nc = j+dc[k];
					if(!valid(nr,nc)) continue;
					if(b[i][j] == 'X' && b[nr][nc] == 'X')
						dsu.union(map(i,j), map(nr,nc));
				}
			}
		}

		box = new int[R][C];
		for(int a[] : box) Arrays.fill(a, -1);

		ArrayDeque<Pair> q = new ArrayDeque<Pair>();
		for(int i = 0; i < R; i++)
			for(int j = 0; j < C; j++)
				if(b[i][j] == '.') {q.add(new Pair(i,j)); box[i][j] = 0;}
		while(!q.isEmpty()) {
			Pair p = q.poll();
			for(int k = 0; k < dr.length; k++) {
				int nr = p.r+dr[k];
				int nc = p.c+dc[k];
				if(!valid(nr,nc) || box[nr][nc] != -1) continue;
				box[nr][nc] = box[p.r][p.c]+1;
				q.add(new Pair(nr,nc));
			}
		}

		int max[] = new int[R*C];
		Arrays.fill(max, -1);
		for(int i = 0; i < R; i++) {
			for(int j = 0; j < C; j++) {
				if(box[i][j] == 0) continue;
				int m = map(i,j);
				int d = dsu.find(m);
				max[d] = Math.max(max[d], box[i][j]);
			}
		}

		int maxPrint = 14214124;
		for(int i = 0; i < R*C; i++) {
			if(max[i] != -1) maxPrint = Math.min(maxPrint, max[i]);
		}

		out.println((maxPrint-1));
		for(int i = 1; i < R-1; i++) {
			for(int j = 1; j < C-1; j++) {
				if(box[i][j] >= maxPrint) out.print('X');
				else out.print('.');
			}out.println();
		}
		out.close();
	}

	static class Pair{
		int r,c;
		public Pair(int rr, int cc) {
			r=rr;
			c=cc;
		}
	}

	static boolean valid(int r, int c) {
		return r >= 0 && r < R && c >= 0 && c < C;
	}
	static int map(int r, int c) {
		return C*r + c;
	}

	static class DisjointSet {
		int[] s;

		public DisjointSet(int n) {
			Arrays.fill(s = new int[n], -1);
		}

		public int find(int i) {
			return s[i] < 0 ? i : (s[i] = find(s[i]));
		}

		public boolean union(int a, int b) {
			if ((a = find(a)) == (b = find(b))) return false;
			if(s[a] == s[b]) s[a]--;
			if(s[a] <= s[b]) s[b] = a; else s[a] = b;
			return true;
		}
	}

	static class FS{
		BufferedReader br;
		StringTokenizer st;
		public FS() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}
		String next() {
			while(st == null || !st.hasMoreElements()) {
				try {st = new StringTokenizer(br.readLine());}
				catch(Exception e) { throw null;}
			}
			return st.nextToken();
		}
		int nextInt() { return Integer.parseInt(next());}
		double nextDouble() { return Double.parseDouble(next());}
		long nextLong() { return Long.parseLong(next());}
		int[] NIA(int n) {
			int r[] = new int[n];
			for(int i = 0; i < n; i++) r[i] = nextInt();
			return r;
		}
		long[] NLA(int n) {
			long r[] = new long[n];
			for(int i = 0; i < n; i++) r[i] = nextLong();
			return r;
		}
		char[][] grid(int r, int c){
			char res[][] = new char[r][c];
			for(int i = 0; i < r; i++) {
				char l[] = next().toCharArray();
				for(int j = 0; j < c; j++) {
					res[i][j] = l[j];
				}
			}
			return res;
		}
	}

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.SortedMap;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * https://codeforces.com/contest/1261/problem/C
 */
public class TaskC {
    public static void main(String[] arg) {
        final FastScanner in = new FastScanner(System.in);
        final PrintWriter out = new PrintWriter(System.out);
        final int n = in.nextInt();
        final int m = in.nextInt();
        char[][] forest = new char[n][];
        for(int i=0;i<n;i++){
            forest [i] =  in.next().toCharArray();
        }
        Solution sol = new Solution(forest);
        sol.bfs();
        sol.checkSolution(out);
        out.close();
        in.close();
    }
    public static class Solution {
        private final char [][] forest;
        private final Map<Integer,List<int[]>> pA = new HashMap<>();
        private final int[][] mem;

        public Solution(char [][] forest){
            this.forest=forest;
            mem = new int[forest.length][forest[0].length];
        }

        public  void bfs() {

            for(int i=0;i<mem.length;i++){
                for(int j=0;j<mem[i].length;j++){
                    if(forest[i][j]=='.') {
                        mem[i][j] = -1;
                    }
                }
            }

            Queue<int[]> toVisit = new LinkedList<>();
            for (int i = 0; i < forest.length; i++) {
                for (int j = 0; j < forest[i].length; j++) {
                    if (forest[i][j]=='X' && border(i, j)) {
                        toVisit.add(new int[]{i, j});
                        mem[i][j]=1;
                        addToMap(1,new int[]{i,j});
                    }
                }
            }

            while(!toVisit.isEmpty()){
                int [] point = toVisit.poll();
                List<int[]> notVisited = notVisited(point[0],point[1],mem);
                for(int[]p:notVisited){
                    mem[p[0]][p[1]]=mem[point[0]][point[1]]+1;
                    toVisit.add(p);
                    addToMap(mem[p[0]][p[1]], p);
                }
            }

        }

        public void checkSolution(PrintWriter out){
            int[] keys = pA.keySet().stream().sorted().mapToInt(i->i).toArray();

//            int l = 0;
//            int h = keys.length-1;
//            int m=(l+h+1)/2;
//            while(l!=h){
//                int key= keys[m];
//                if(runFireBFS(key)){
//                    l=m;
//                }
//                else{
//                    h=m-1;
//                }
//                m=(l+h+1)/2;
//            }
            int h =0;
            for(h=keys.length-1;h>=0;h--){
                if(runFireBFS(h)){
                    break;
                }
            }
            printAnsw(keys[h], out);
            return;
        }

        public void printAnsw(int key, PrintWriter out){
            char[][] iF = new char[forest.length][forest[0].length];
            for(int x=0;x<iF.length;x++){
                for(int y=0;y<iF[x].length;y++){
                    iF[x][y]='.';
                    if(mem[x][y]>=key){
                        iF[x][y]='X';
                    }
                }
            }
            out.printf("%d%n",key-1);
            for(int x=0;x<iF.length;x++){
                out.println(String.valueOf(iF[x]));
            }
        }

        public boolean runFireBFS(int key){
            Queue<int[]> q = new LinkedList<>();
            //init
            int step = 1;
            int [][] m = new int[forest.length][forest[0].length];
           for(int i=0;i<mem.length;i++){
               for(int j=0;j<mem[i].length;j++) {
                   if(mem[i][j]>=key) {
                       int x = i;
                       int y = j;
                       q.add(new int[]{step, x, y});
                       m[i][j] = 1;
                   }
               }
           }

           while(!q.isEmpty()&&step<=key){
              int [] fire = q.poll();
              step=fire[0];
              m[fire[1]][fire[2]]=step;
              List<int[]> spred = spredFire(fire[1],fire[2],m);
              for(int[] nF:spred){
                 int x = nF[0];
                 int y = nF[1];
                 int nS=step+1;
                 if(nS<=key) {
                     if (forest[x][y] == '.') {
                         return false;
                     }
                     m[x][y]=nS;
                     q.add(new int[]{nS, x, y});
                 }
              }
           }

           for(int i=0;i<forest.length;i++){
               for(int j=0;j<forest[i].length;j++){
                   if(m[i][j]==0 &&forest[i][j]=='X'){
                      return false;
                   }
                   if(m[i][j]!=0&&forest[i][j]=='.'){
                       return false;
                   }
               }
           }
           return true;
        }

        private List<int[]> spredFire(int x, int y, int[][] mem) {
            List<int[]> result = new ArrayList<>();
            for(int i=x-1;i<=x+1;i++){
                if(i<0){continue;}
                if(i>=mem.length){continue;}
                for(int j=y-1;j<=y+1;j++){
                    if(j<0){continue;}
                    if(j>=mem[i].length){continue;}
                    if(mem[i][j]!=0){
                        continue;
                    }
                    result.add(new int[]{i,j});
                }
            }
            return result;
        }

        public void addToMap(int key, int[] point) {
            List<int[]> points = pA.get(key);
            if(points==null){
                points = new ArrayList<>();
                pA.put(key,points);
            }
            points.add(point);
        }

        private List<int[]> notVisited(final int x, final int y, int [][] mem){
            List<int[]> result = new LinkedList<>();
            for(int i=x-1;i<=x+1;i++){
                if(i<0){continue;}
                if(i>=mem.length){
                    continue;
                }
                for(int j=y-1;j<=y+1;j++){
                    if(j<0){continue;}
                    if(j>=mem[i].length){continue;}
                    if(mem[i][j]==0){
                        result.add(new int[]{i,j});
                    }
                }
            }
            return result;
        }

        private boolean border(final int x, final int y){
            for(int i=x-1;i<=x+1;i++){
                if(i<0) {return true;}
                if(i>=forest.length){return true;}
                for(int j=y-1;j<=y+1;j++){
                    if(j<0){return true;}
                    if(i==j){continue;}
                    if(j>=forest[i].length){return true;}
                    if(forest[i][j]=='.'){
                        return true;
                    }
                }
            }
            return false;
        }
    }
    private static void printMatrix(int [][] forest){
        for(int i=0;i<forest.length;i++){
            for(int j=0;j<forest[i].length;j++){
                System.out.printf("%3d",forest[i][j]);
            }
            System.out.printf("%n");
        }
    }

    private static void printMatrix(char [][] forest){
        for(int i=0;i<forest.length;i++){
            for(int j=0;j<forest[i].length;j++){
                System.out.printf("%c",forest[i][j]);
            }
            System.out.printf("%n");
        }
    }

    private static class FastScanner {
        BufferedReader br;
        StringTokenizer st;

        FastScanner(InputStream stream) {
            try {
                br = new BufferedReader(new InputStreamReader(stream));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        String next() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        int[] readIntArr(int n) {
            int[] result = new int[n];
            for (int i = 0; i < n; i++) {
                result[i] = Integer.parseInt(next());
            }
            return result;
        }

        void close() {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        long nextLong() {
            return Long.parseLong(next());
        }

    }

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.SortedMap;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * https://codeforces.com/contest/1261/problem/C
 */
public class TaskC {
    public static void main(String[] arg) {
        final FastScanner in = new FastScanner(System.in);
        final PrintWriter out = new PrintWriter(System.out);
        final int n = in.nextInt();
        final int m = in.nextInt();
        char[][] forest = new char[n][];
        for(int i=0;i<n;i++){
            forest [i] =  in.next().toCharArray();
        }
        Solution sol = new Solution(forest);
        sol.bfs();
        sol.checkSolution(out);
        out.close();
        in.close();
    }
    private static class Solution{
        private final char [][] forest;
        private final Map<Integer,List<int[]>> pA = new HashMap<>();

        public Solution(char [][] forest){
            this.forest=forest;
        }

        public  void bfs() {
            int[][] mem = new int[forest.length][forest[0].length];
            for(int i=0;i<mem.length;i++){
                for(int j=0;j<mem[i].length;j++){
                    if(forest[i][j]=='.') {
                        mem[i][j] = -1;
                    }
                }
            }

            Queue<int[]> toVisit = new LinkedList<>();
            for (int i = 0; i < forest.length; i++) {
                for (int j = 0; j < forest[i].length; j++) {
                    if (forest[i][j]=='X' && border(i, j)) {
                        toVisit.add(new int[]{i, j});
                        mem[i][j]=1;
                        addToMap(1,new int[]{i,j});
                    }
                }
            }

            while(!toVisit.isEmpty()){
                int [] point = toVisit.poll();
                List<int[]> notVisited = notVisited(point[0],point[1],mem);
                for(int[]p:notVisited){
                    mem[p[0]][p[1]]=mem[point[0]][point[1]]+1;
                    toVisit.add(p);
                    addToMap(mem[p[0]][p[1]], p);
                }
            }

        }

        public List<int[]> checkSolution(PrintWriter out){
            int[] keys = pA.keySet().stream().sorted().mapToInt(i->i).toArray();
            List<int[]> initialFire = new ArrayList<>();
            for(int i=keys.length-1;i>=0;i--){
                int key= keys[i];
                initialFire.addAll(pA.get(key));
                if(runFireBFS(key,initialFire)){

                    char[][] iF = new char[forest.length][forest[0].length];
                    for(int x=0;x<iF.length;x++){
                        for(int y=0;y<iF[x].length;y++){
                            iF[x][y]='.';
                        }
                    }
                    for(int []p:initialFire){
                        iF[p[0]][p[1]]='X';
                    }
                    out.printf("%d%n",key-1);
                    for(int x=0;x<iF.length;x++){
                        out.println(String.valueOf(iF[x]));
                    }
                    return initialFire;
                }
            }
            return initialFire;
        }

        public boolean runFireBFS(int key, List<int[]> initialFire){
            Queue<int[]> q = new LinkedList<>();
            //init
            int step = 1;
            int [][] mem = new int[forest.length][forest[0].length];
           for(int [] fp:initialFire){

               int x =fp[0];
               int y= fp[1];
               q.add(new int[]{step,x,y});
               mem[x][y]=1;
           }

           while(!q.isEmpty()&&step<=key){
              int [] fire = q.poll();
              step=fire[0];
              mem[fire[1]][fire[2]]=step;
              List<int[]> spred = spredFire(fire[1],fire[2],mem);
              for(int[] nF:spred){
                 int x = nF[0];
                 int y = nF[1];
                 int nS=step+1;
                 if(nS<=key) {
                     if (forest[x][y] == '.') {
                         return false;
                     }
                     q.add(new int[]{nS, x, y});
                 }
              }
           }

           for(int i=0;i<forest.length;i++){
               for(int j=0;j<forest[i].length;j++){
                   if(mem[i][j]==0 &&forest[i][j]=='X'){
                                    //printMatrix(mem);
                      return false;
                   }
                   if(mem[i][j]!=0&&forest[i][j]=='.'){

                       return false;
                   }
               }
           }
           return true;
        }

        private List<int[]> spredFire(int x, int y, int[][] mem) {
            List<int[]> result = new ArrayList<>();
            for(int i=x-1;i<=x+1;i++){
                if(i<0){continue;}
                if(i>=mem.length){continue;}
                for(int j=y-1;j<=y+1;j++){
                    if(j<0){continue;}
                    if(j>=mem[i].length){continue;}
                    if(mem[i][j]!=0){
                        continue;
                    }
                    result.add(new int[]{i,j});
                }
            }
            return result;
        }

        public void addToMap(int key, int[] point) {
            List<int[]> points = pA.get(key);
            if(points==null){
                points = new ArrayList<>();
                pA.put(key,points);
            }
            points.add(point);
        }

        private List<int[]> notVisited(final int x, final int y, int [][] mem){
            List<int[]> result = new LinkedList<>();
            for(int i=x-1;i<=x+1;i++){
                if(i<0){continue;}
                if(i>=mem.length){
                    continue;
                }
                for(int j=y-1;j<=y+1;j++){
                    if(j<0){continue;}
                    if(j>=mem[i].length){continue;}
                    if(mem[i][j]==0){
                        result.add(new int[]{i,j});
                    }
                }
            }
            return result;
        }

        private boolean border(final int x, final int y){
            for(int i=x-1;i<=x+1;i++){
                if(i<0) {return true;}
                if(i>=forest.length){return true;}
                for(int j=y-1;j<=y+1;j++){
                    if(j<0){return true;}
                    if(i==j){continue;}
                    if(j>=forest[i].length){return true;}
                    if(forest[i][j]=='.'){
                        return true;
                    }
                }
            }
            return false;
        }
    }
    private static void printMatrix(int [][] forest){
        for(int i=0;i<forest.length;i++){
            for(int j=0;j<forest[i].length;j++){
                System.out.printf("%3d",forest[i][j]);
            }
            System.out.printf("%n");
        }
    }

    private static void printMatrix(char [][] forest){
        for(int i=0;i<forest.length;i++){
            for(int j=0;j<forest[i].length;j++){
                System.out.printf("%c",forest[i][j]);
            }
            System.out.printf("%n");
        }
    }

    private static class FastScanner {
        BufferedReader br;
        StringTokenizer st;

        FastScanner(InputStream stream) {
            try {
                br = new BufferedReader(new InputStreamReader(stream));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        String next() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        int[] readIntArr(int n) {
            int[] result = new int[n];
            for (int i = 0; i < n; i++) {
                result[i] = Integer.parseInt(next());
            }
            return result;
        }

        void close() {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        long nextLong() {
            return Long.parseLong(next());
        }

    }

}