#include<bits/stdc++.h>
using namespace std;
const int maxn=1200;
char mapp[1200][1200];
int vis[maxn][maxn];
int belong[maxn][maxn];
int dir[4][2]={0,1,1,0,0,-1,-1,0};
int du[maxn];
struct node
{
	int x,y;
}head,tail;
int n,m;
int block=0;
int viss[maxn];
int answer[maxn][maxn];
void bfs(int x,int y)
{
	queue<node>q;
	head.x=x;
	head.y=y;
	vis[x][y]=1;
	q.push(head);
	++block;
	while(!q.empty())
	{
		node now;
		now=q.front();
		q.pop();
		belong[now.x][now.y]=block;
		du[block]++;
		for(int i=0;i<4;i++)
		{
			tail.x=now.x+dir[i][0];
			tail.y=now.y+dir[i][1];
			if(tail.x>=1&&tail.x<=n&&tail.y>=1&&tail.y<=m)
			{
				if(vis[tail.x][tail.y]==0&&mapp[tail.x][tail.y]=='.')
				{
					vis[tail.x][tail.y]=1;
					q.push(tail);
				}
			}
		}
	}
}
int main ()
{
	scanf("%d%d",&n,&m);
	memset(vis,0,sizeof(vis));
	memset(mapp,0,sizeof(mapp));
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			scanf(" %c",&mapp[i][j]);
		}
	}
	memset(belong,-1,sizeof(belong));
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			answer[i][j]=1;
			if(mapp[i][j]=='.'&&vis[i][j]==0)
			{
				bfs(i,j);
			}
		}
	}
	/*for(int i=1;i<=block;i++)
	{
		printf("%d\n",du[i]);
	}*/
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			if(mapp[i][j]=='*')
			{
				memset(viss,0,sizeof(viss));
				for(int tt=0;tt<4;tt++)
				{
					int xx,yy;
					int flag=0;
					xx=i+dir[tt][0];
					yy=j+dir[tt][1];
					if(xx<1||yy<1||xx>n||yy>m)
						continue;
					if(belong[xx][yy]!=-1&&viss[belong[xx][yy]]==0)
					{
						viss[belong[xx][yy]]=1;
						answer[i][j]+=du[belong[xx][yy]];
					}
				}
			}
		}
	}
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			if(mapp[i][j]=='.')
			{
				printf(".");
			}
			else
			{
				printf("%d",answer[i][j]%10);
			}
		}
		printf("\n");
	}
}


#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int maxn=1010;
char map[maxn][maxn];
int num[maxn][maxn];
bool vis[maxn][maxn];
int dirx[]= {0,1,0,-1};
int diry[]= {1,0,-1,0};
int n,m;
bool judge(int x,int y)
{
    if(x>=0&&y>=0&&x<n&&y<m&&map[x][y]!='*'&&!vis[x][y])
        return true;
    return false;
}
void bfs(int x,int y)
{
    pair<int,int> now=make_pair(x,y);
    int a=now.first;
    int b=now.second;
    queue<pair<int,int> > que;
    que.push(now);
    vis[now.first][now.second]=true;
    int cnt=1;
    while(!que.empty())
    {
        pair<int,int> pa=que.front();
        que.pop();
        for(int i=0; i<4; i++)
        {
            int nx=pa.first+dirx[i];
            int ny=pa.second+diry[i];
            if(judge(nx,ny))
            {
                cnt++;
                vis[nx][ny]=true;
                que.push(make_pair(nx,ny));
            }
        }
    }
    num[a][b]=cnt;
    return;
}
int main()
{
    scanf("%d%d",&n,&m);
    getchar();
    for(int i=0; i<n; i++)
    {
		scanf("%s",map[i]);
    }
    for(int i=0; i<n; i++)
    {
        for(int j=0; j<m; j++)
        {
            if(map[i][j]=='*')
            {
                memset(vis,false,sizeof(vis));
                bfs(i,j);
            }
        }
    }
    for(int i=0; i<n; i++)
    {
        for(int j=0; j<m; j++)
        {
            if(map[i][j]=='*')
            {
                printf("%d",num[i][j]%10);
            }
            else
                putchar(map[i][j]);
        }
        puts("");
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
const int maxn=1200;
char mapp[1200][1200];
int vis[maxn][maxn];
int belong[maxn][maxn];
int dir[4][2]={0,1,1,0,0,-1,-1,0};
set<int>ss;
		set<int> ::iterator it;
int du[maxn*maxn];
struct node
{
	int x,y;
}head,tail;
int n,m;
int block=0;
int a[5];
int answer[maxn][maxn];
void bfs(int x,int y)
{
	queue<node>q;
	head.x=x;
	head.y=y;
	vis[x][y]=1;
	q.push(head);
	++block;
	while(!q.empty())
	{
		node now;
		now=q.front();
		q.pop();
		belong[now.x][now.y]=block;
		du[block]++;
		for(int i=0;i<4;i++)
		{
			tail.x=now.x+dir[i][0];
			tail.y=now.y+dir[i][1];
			if(tail.x>=1&&tail.x<=n&&tail.y>=1&&tail.y<=m)
			{
				if(vis[tail.x][tail.y]==0&&mapp[tail.x][tail.y]=='.')
				{
					vis[tail.x][tail.y]=1;
					q.push(tail);
				}
			}
		}
	}
}
int main ()
{
	scanf("%d%d",&n,&m);
	memset(vis,0,sizeof(vis));
	memset(mapp,0,sizeof(mapp));
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			scanf(" %c",&mapp[i][j]);
		}
	}
	memset(belong,-1,sizeof(belong));
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			answer[i][j]=1;
			if(mapp[i][j]=='.'&&vis[i][j]==0)
			{
				bfs(i,j);
			}
		}
	}
	/*for(int i=1;i<=block;i++)
	{
		printf("%d\n",du[i]);
	}*/
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			ss.clear();
			if(mapp[i][j]=='*')
			{
				for(int k=0;k<4;k++)
				{
					int xx,yy;
					xx=i+dir[k][0];
					yy=j+dir[k][1];
					if(xx>=1&&yy>=1&&xx<=n&&yy<=m&&mapp[xx][yy]=='.')
					{
						ss.insert(belong[xx][yy]);
					}
				}
				for(it=ss.begin();it!=ss.end();it++)
				{
					answer[i][j]+=du[*it];
				}
			}
		}
	}
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			if(mapp[i][j]=='.')
			{
				printf(".");
			}
			else
			{
				printf("%d",answer[i][j]%10);
			}
		}
		printf("\n");
	}


#include<cstdio>
#include<iostream>
#include<queue>
#include<cstring>
#include<stack>
using namespace std;
int n,m;
struct node{
	int x,y;

}te;
char p[1005][1005];
int ans[1001][1001],col[1001][1001],sum[1001],book[1001];
node dot[1000001];
int ne[4][2]={1,0,0,1,-1,0,0,-1};
void bfs(int x,int y,int c){

	int i,j,tx,ty;
	queue <node> q;
	te.x=x;te.y=y;
	q.push(te);
	while(!q.empty())
    {
		for(i=0;i<4;i++)
		{
			tx=q.front().x+ne[i][0];
            ty=q.front().y+ne[i][1];
			if(tx<0||ty<0||tx>=n||ty>=m)
                continue;
			if(p[tx][ty]=='.'&&!col[tx][ty])
			{
				col[tx][ty]=c;
				sum[c]++;
				te.x=tx;
                te.y=ty;
				q.push(te);
			}
		}
		q.pop();
	}
	return ;
}
int main(){
	int i,j,co=0,c,xx,xy;
	scanf("%d %d",&n,&m);
	getchar();
	for(i=0;i<n;i++)
    {
		for(j=0;j<m;j++)
		{
			scanf("%c",&p[i][j]);
			if(p[i][j]=='*')
			{
				dot[co].x=i;dot[co].y=j;
				co++;
			}
		}
		getchar();
	}

    c=1;
	for(i=0;i<n;i++)
	{
		for(j=0;j<m;j++)
        {
			if(p[i][j]=='.'&&!col[i][j])
			{
				col[i][j]=c;
				sum[c]=1;
				bfs(i,j,c);
			}
			c++;
		}
	}
//	for(int i=0;i<n;i++)
//    {
//        for(int j=0;j<m;j++)
//            printf("%d",sum[col[i][j]]);
//        printf("\n");
//    }
	for(i=0;i<n;i++)
	{
		for(j=0;j<m;j++)
        {
            ans[i][j]=0;
			if(p[i][j]=='*')
            {
				memset(book,0,sizeof(book));
				for(int k=0;k<4;k++)
				{
					xx=i+ne[k][0];xy=j+ne[k][1];
					if(xx<0||xy<0||xx>=n||xy>=m)continue;
					if(!book[col[xx][xy]])
					{
						ans[i][j]+=sum[col[xx][xy]];
						book[col[xx][xy]]=1;
					}
				}
				ans[i][j]++;
			}
		}
	}
	for(i=0;i<n;i++)
    {
		for(j=0;j<m;j++)
		{
			if(p[i][j]=='*')
			cout<<(ans[i][j]%10);
			else
			cout<<p[i][j];
		}
		cout<<endl;
	}
	return 0;
}


#include<cstdio>
#include<iostream>
#include<queue>
#include<cstring>
#include<stack>
using namespace std;
int n,m;
struct node{
	int x,y;

}te;
char p[1005][1005];
int ans[1001][1001],col[1001][1001],sum[1001],book[1001];
node dot[1000001];
int ne[4][2]={1,0,0,1,-1,0,0,-1};
void bfs(int x,int y,int c){

	int i,j,tx,ty;
	queue <node> q;
	te.x=x;te.y=y;
	q.push(te);
	while(!q.empty())
    {
		for(i=0;i<4;i++)
		{
			tx=q.front().x+ne[i][0];
            ty=q.front().y+ne[i][1];
			if(tx<0||ty<0||tx>=n||ty>=m)
                continue;
			if(p[tx][ty]=='.'&&!col[tx][ty])
			{
				col[tx][ty]=c;
				sum[c]++;
				te.x=tx;
                te.y=ty;
				q.push(te);
			}
		}
		q.pop();
	}
	return ;
}
int main(){
	int i,j,co=0,c,xx,xy;
	scanf("%d %d",&n,&m);
	getchar();
	for(i=0;i<n;i++)
    {
		for(j=0;j<m;j++)
		{
			scanf("%c",&p[i][j]);
			if(p[i][j]=='*')
			{
				dot[co].x=i;dot[co].y=j;
				co++;
			}
		}
		getchar();
	}

    c=1;
	for(i=0;i<n;i++)
	{
		for(j=0;j<m;j++)
        {
			if(p[i][j]=='.'&&!col[i][j])
			{
				col[i][j]=c;
				sum[c]=1;
				bfs(i,j,c);
			}
			c++;
		}
	}
//	for(int i=0;i<n;i++)
//    {
//        for(int j=0;j<m;j++)
//            printf("%d",sum[col[i][j]]);
//        printf("\n");
//    }
	for(i=0;i<n;i++)
	{
		for(j=0;j<m;j++)
        {
			if(p[i][j]=='*')
            {
				memset(book,0,sizeof(book));
				for(int k=0;k<4;k++)
				{
					xx=i+ne[k][0];xy=j+ne[k][1];
					if(xx<0||xy<0||xx>n||xy>m)continue;
					if(!book[col[xx][xy]])
					{
						ans[i][j]+=sum[col[xx][xy]];
						book[col[xx][xy]]=1;
					}
				}
				ans[i][j]++;
			}
		}
	}
	for(i=0;i<n;i++)
    {
		for(j=0;j<m;j++)
		{
			if(p[i][j]=='*')
			cout<<(ans[i][j]%10);
			else
			cout<<p[i][j];
		}
		cout<<endl;
	}
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
int dir[4][2]={0,1,1,0,0,-1,-1,0};
char mmap[1111][1111];
int book[1111][1111];
struct xjy
{
    int x;
    int y;
    int step;
    bool operator < (const xjy &r)const
    {
        return step>r.step;
    }
};
int sum[11111111];
int ans=0;
void dfs(int x,int y,int cnt)
{
    for(int i=0;i<4;i++)
    {
    	int midx=x+dir[i][0];
    	int midy=y+dir[i][1];
    	if(mmap[midx][midy]=='.'&&book[midx][midy]==0)
    	{
    		book[midx][midy]=cnt;
    		ans++;
    		dfs(midx,midy,cnt);
    	}
    }
}
int main()
{
    int n,m;
    cin >> n >>m;
    for(int i=0;i<=n+1;i++)
        for(int j=0;j<=m+1;j++)
            mmap[i][j]='*';
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            cin >> mmap[i][j];
        }
    }
    int cnt=1;
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            if(mmap[i][j]=='.')
            {
                if(!book[i][j])
                {
                	ans=1;
                	book[i][j]=cnt;
                    dfs(i,j,cnt);
                    sum[cnt]=ans;
                    cnt++;
                }
            }
        }
    }
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            if(mmap[i][j]=='.')
                cout << ".";
            else
            {
                int ansum=0;
                xjy mid;
                mid.x=i;
                mid.y=j;
                int sset[5];
                int ccnt=0;
                for(int k=0;k<=4;k++)
                    sset[k]=0;
                for(int k=0;k<4;k++)
                {

                    xjy midmid;
                    midmid.x=mid.x+dir[k][0];
                    midmid.y=mid.y+dir[k][1];
                    int flag=1;
                    for(int kk=0;kk<4;kk++)
                        {
                            if(sset[kk]==book[midmid.x][midmid.y])
                                flag=0;
                        }
                    if(flag)
                        sset[ccnt++]=book[midmid.x][midmid.y];
                }
                for(int k=0;k<ccnt;k++)
                {
                    ansum+=sum[sset[k]];
                }
                cout << (ansum+1)%10;
            }
        }
        cout <<endl;
    }
}


#include<bits/stdc++.h>
using namespace std;
int dir[4][2]={0,1,1,0,0,-1,-1,0};
char mmap[1111][1111];
int book[1111][1111];
struct xjy
{
    int x;
    int y;
    int step;
    bool operator < (const xjy &r)const
    {
        return step>r.step;
    }
};
int sum[11111111];
void bfs(int x,int y,int cnt)
{
    xjy mid;
    mid.x=x;
    mid.y=y;
    mid.step=0;
    priority_queue<xjy> q;
    q.push(mid);
    int ans=0;
    while(!q.empty())
    {
        mid=q.top();
        q.pop();
        if(book[mid.x][mid.y])
            continue;
        book[mid.x][mid.y]=cnt;
        ans++;
        xjy midmid;
        for(int i=0;i<4;i++)
        {
            midmid.x=mid.x+dir[i][0];
            midmid.y=mid.y+dir[i][1];
            midmid.step=mid.step+1;
            if(!book[midmid.x][midmid.y]&&mmap[midmid.x][midmid.y]=='.')
            {
                q.push(midmid);
            }
        }
    }
    sum[cnt]=ans;
}
int main()
{
    int n,m;
    cin >> n >>m;
    for(int i=0;i<=n+1;i++)
        for(int j=0;j<=m+1;j++)
            mmap[i][j]='*';
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            scanf(" %c",&mmap[i][j]);
        }
    }
    int cnt=1;
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            if(mmap[i][j]=='.')
            {
                if(!book[i][j])
                {
                    bfs(i,j,cnt++);
                }
            }
        }
    }
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            if(mmap[i][j]=='.')
                printf(".");
            else
            {
                int ansum=0;
                xjy mid;
                mid.x=i;
                mid.y=j;
                int sset[5];
                int ccnt=0;
                for(int k=0;k<=4;k++)
                    sset[k]=0;
                for(int k=0;k<4;k++)
                {

                    xjy midmid;
                    midmid.x=mid.x+dir[k][0];
                    midmid.y=mid.y+dir[k][1];
                    int flag=1;
                    for(int kk=0;kk<4;kk++)
                        {
                            if(sset[kk]==book[midmid.x][midmid.y])
                                flag=0;
                        }
                    if(flag)
                        sset[ccnt++]=book[midmid.x][midmid.y];
                }
                for(int k=0;k<ccnt;k++)
                {
                    ansum+=sum[sset[k]];
                }
                printf("%d",(ansum+1)%10);
            }
        }
        printf("\n");
    }
}


#include<bits/stdc++.h>
#define maxn 1000010
using namespace std;
struct xjy
{
    int x;
    int y;
};
int dir[4][2]={1,0,0,1,-1,0,0,-1};
char mmap[1111][1111];
xjy pre[1111][1111];
int num[1111][1111];
xjy findx(xjy xx)
{
    xjy r=xx;
    while(pre[r.x][r.y].x!=r.x||pre[r.x][r.y].y!=r.y)
        {
            r=pre[r.x][r.y];
        }

    xjy i=xx,j;
    while(pre[i.x][i.y].x!=r.x||pre[i.x][i.y].y!=r.y)
    {
        j=pre[i.x][i.y];
        pre[i.x][i.y]=r;
        i=j;
    }
    return r;
}
void join (xjy xx,xjy yy)
{
    xjy p1=findx(xx);
    xjy p2=findx(yy);
    if(p1.x!=p2.x||p1.y!=p2.y)
        {
            pre[p1.x][p1.y]=p2;
            num[p2.x][p2.y]+=num[p1.x][p1.y];
            num[p1.x][p1.y]=0;
        }
}
int main()
{
    for(int i=0;i<=1001;i++)
        for(int j=0;j<=1001;j++)
    {
        xjy mid;
        mid.x=i;
        mid.y=j;
        pre[i][j]=mid;
        num[i][j]=0;
        mmap[i][j]='*';
    }
    int n,m;
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
        {
            char c;
            scanf(" %c",&c);
            if(c=='.')
                {
                    mmap[i][j]=c;
                    num[i][j]=1;
                }
            else
                mmap[i][j]=c;
        }

     for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
        {
            if(mmap[i][j]=='.')
           {
                xjy mid;
                mid.x=i;
                mid.y=j;
                xjy midmid;
                for(int ii=0;ii<4;ii++)
                {
                    midmid.x=mid.x+dir[ii][0];
                    midmid.y=mid.y+dir[ii][1];
                    if(mmap[midmid.x][midmid.y]=='.')
                    {
                        join(mid,midmid);
                    }
                }
            }
        }
    for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=m;j++)
        {
            if(mmap[i][j]=='*')
            {
                int sum=0;
                xjy mid;
                mid.x=i;
                mid.y=j;
                vector<xjy > sss;
                for(int ii=0;ii<4;ii++)
                {
                    xjy midmid;
                    midmid.x=mid.x+dir[ii][0];
                    midmid.y=mid.y+dir[ii][1];
                    if(mmap[midmid.x][midmid.y]=='.')
                    {
                        sum=0;
                        midmid=findx(midmid);
                        //printf("%d %d\n",midmid.x,midmid.y);
                        //printf("%d\n",sss.size());
                        if(sss.size()==0)
                            sss.push_back(midmid);
                        else
                        {
                            int eend=sss.size();
                            int flag=1;
                            for(int it=0;it!=eend;it++)
                                if(midmid.x==sss[it].x&&midmid.y==sss[it].y)
                                    {
                                        flag=0;
                                    }
                            if(flag)
                                sss.push_back(midmid);
                        }
                    }
                }
                for(int it=0;it!=sss.size();it++)
                {
                    xjy midmidmid=findx(sss[it]);
                    int midx=midmidmid.x;
                    int midy=midmidmid.y;
                    sum+=num[midx][midy];
                }
                printf("%d",(sum+1)%10);
            }
            else
                printf("%c",mmap[i][j]);
        }
        printf("\n");
        }

}


#include<bits/stdc++.h>
using namespace std;
int dir[4][2]={0,1,1,0,0,-1,-1,0};
char mmap[1111][1111];
int book[1111][1111];
int sum[11111111];
int ans=0;
void dfs(int x,int y,int cnt)
{
    for(int i=0;i<4;i++)
    {
    	int midx=x+dir[i][0];
    	int midy=y+dir[i][1];
    	if(mmap[midx][midy]=='.'&&book[midx][midy]==0)
    	{
    		book[midx][midy]=cnt;
    		ans++;
    		dfs(midx,midy,cnt);
    	}
    }
}
int main()
{
    int n,m;
    cin >> n >>m;
    for(int i=0;i<=n+1;i++)
        for(int j=0;j<=m+1;j++)
            mmap[i][j]='*';
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            cin >> mmap[i][j];
        }
    }
    int cnt=1;
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            if(mmap[i][j]=='.')
            {
                if(!book[i][j])
                {
                	ans=1;
                	book[i][j]=cnt;
                    dfs(i,j,cnt);
                    sum[cnt]=ans;
                    cnt++;
                }
            }
        }
    }
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            if(mmap[i][j]=='.')
                cout << ".";
            else
            {
                int ansum=0;
                xjy mid;
                mid.x=i;
                mid.y=j;
                int sset[5];
                int ccnt=0;
                for(int k=0;k<=4;k++)
                    sset[k]=0;
                for(int k=0;k<4;k++)
                {

                    xjy midmid;
                    midmid.x=mid.x+dir[k][0];
                    midmid.y=mid.y+dir[k][1];
                    int flag=1;
                    for(int kk=0;kk<4;kk++)
                        {
                            if(sset[kk]==book[midmid.x][midmid.y])
                                flag=0;
                        }
                    if(flag)
                        sset[ccnt++]=book[midmid.x][midmid.y];
                }
                for(int k=0;k<ccnt;k++)
                {
                    ansum+=sum[sset[k]];
                }
                cout << (ansum+1)%10;
            }
        }
        cout <<endl;
    }
}


#include<bits/stdc++.h>
using namespace std;
const int maxn=1200;
char mapp[1200][1200];
int vis[maxn][maxn];
int belong[maxn][maxn];
int dir[4][2]={0,1,1,0,0,-1,-1,0};
int du[maxn];
struct node
{
	int x,y;
}head,tail;
int n,m;
int block=0;
int a[5];
int answer[maxn][maxn];
void bfs(int x,int y)
{
	queue<node>q;
	head.x=x;
	head.y=y;
	vis[x][y]=1;
	q.push(head);
	++block;
	while(!q.empty())
	{
		node now;
		now=q.front();
		q.pop();
		belong[now.x][now.y]=block;
		du[block]++;
		for(int i=0;i<4;i++)
		{
			tail.x=now.x+dir[i][0];
			tail.y=now.y+dir[i][1];
			if(tail.x>=1&&tail.x<=n&&tail.y>=1&&tail.y<=m)
			{
				if(vis[tail.x][tail.y]==0&&mapp[tail.x][tail.y]=='.')
				{
					vis[tail.x][tail.y]=1;
					q.push(tail);
				}
			}
		}
	}
}
int main ()
{
	scanf("%d%d",&n,&m);
	memset(vis,0,sizeof(vis));
	memset(mapp,0,sizeof(mapp));
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			scanf(" %c",&mapp[i][j]);
		}
	}
	memset(belong,-1,sizeof(belong));
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			answer[i][j]=1;
			if(mapp[i][j]=='.'&&vis[i][j]==0)
			{
				bfs(i,j);
			}
		}
	}
	/*for(int i=1;i<=block;i++)
	{
		printf("%d\n",du[i]);
	}*/
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			memset(a,0,sizeof(a));
			if(mapp[i][j]=='*')
			{
				for(int tt=0;tt<4;tt++)
				{
					int xx,yy;
					xx=i+dir[tt][0];
					yy=j+dir[tt][1];
					if(xx<1||yy<1||xx>n||yy>m)
						continue;

					if(belong[xx][yy]!=-1)
					{
						a[tt]=belong[xx][yy];
						//answer[i][j]+=du[belong[xx][yy]];
					}
				}
				for(int tt=0;tt<4;tt++)
				{
					int xx,yy;
					int flag=0;
					xx=i+dir[tt][0];
					yy=j+dir[tt][1];
					if(xx<1||yy<1||xx>n||yy>m)
						continue;
					if(belong[xx][yy]==-1)
					{
						continue;
					}
					for(int t=0;t<tt;t++)
					{
						int x,y;
						x=i+dir[t][0];
						y=j+dir[t][1];
						if(x<1||y<1||x>n||y>m)
							continue;
						if(belong[x][y]==a[tt])
						{
							flag=1;
							break;
						}
					}
					if(flag==0)
					{
						answer[i][j]+=du[belong[xx][yy]];
					}
				}
			}
		}
	}
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			if(mapp[i][j]=='.')
			{
				printf(".");
			}
			else
			{
				printf("%d",answer[i][j]%10);
			}
		}
		printf("\n");
	}
}


#include<bits/stdc++.h>
using namespace std;
const int maxn=1200;
char mapp[1200][1200];
int vis[maxn][maxn];
int belong[maxn][maxn];
int dir[4][2]={0,1,1,0,0,-1,-1,0};
set<int>ss;
		set<int> ::iterator it;
int du[maxn*maxn];
struct node
{
	int x,y;
}head,tail;
int n,m;
int block=0;
int a[5];
int answer[maxn][maxn];
void bfs(int x,int y)
{
	queue<node>q;
	head.x=x;
	head.y=y;
	vis[x][y]=1;
	q.push(head);
	++block;
	while(!q.empty())
	{
		node now;
		now=q.front();
		q.pop();
		belong[now.x][now.y]=block;
		du[block]++;
		for(int i=0;i<4;i++)
		{
			tail.x=now.x+dir[i][0];
			tail.y=now.y+dir[i][1];
			if(tail.x>=1&&tail.x<=n&&tail.y>=1&&tail.y<=m)
			{
				if(vis[tail.x][tail.y]==0&&mapp[tail.x][tail.y]=='.')
				{
					vis[tail.x][tail.y]=1;
					q.push(tail);
				}
			}
		}
	}
}
int main ()
{
	scanf("%d%d",&n,&m);
	memset(vis,0,sizeof(vis));
	memset(mapp,0,sizeof(mapp));
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			scanf(" %c",&mapp[i][j]);
		}
	}
	memset(belong,-1,sizeof(belong));
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			answer[i][j]=1;
			if(mapp[i][j]=='.'&&vis[i][j]==0)
			{
				bfs(i,j);
			}
		}
	}
	/*for(int i=1;i<=block;i++)
	{
		printf("%d\n",du[i]);
	}*/
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			ss.clear();
			if(mapp[i][j]=='*')
			{
				for(int k=0;k<4;k++)
				{
					int xx,yy;
					xx=i+dir[k][0];
					yy=j+dir[k][1];
					if(xx>=1&&yy>=1&&xx<=n&&yy<=m&&mapp[xx][yy]=='.')
					{
						ss.insert(belong[xx][yy]);
					}
				}
				for(it=ss.begin();it!=ss.end();it++)
				{
					answer[i][j]+=du[*it];
				}
			}
		}
	}
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			if(mapp[i][j]=='.')
			{
				printf(".");
			}
			else
			{
				printf("%d",answer[i][j]%10);
			}
		}
		printf("\n");
	}
}


#include<bits/stdc++.h>
using namespace std;
int dir[4][2]={0,1,1,0,0,-1,-1,0};
char mmap[1111][1111];
int book[1111][1111];
set<int > sset;
set<int > ::iterator it;
struct xjy
{
    int x;
    int y;
    int step;
    bool operator < (const xjy &r)const
    {
        return step>r.step;
    }
};
int sum[11111111];
void bfs(int x,int y,int cnt)
{
    xjy mid;
    mid.x=x;
    mid.y=y;
    mid.step=0;
    priority_queue<xjy> q;
    q.push(mid);
    int ans=0;
    while(!q.empty())
    {
        mid=q.top();
        q.pop();
        if(book[mid.x][mid.y])
            continue;
        book[mid.x][mid.y]=cnt;
        ans++;
        xjy midmid;
        for(int i=0;i<4;i++)
        {
            midmid.x=mid.x+dir[i][0];
            midmid.y=mid.y+dir[i][1];
            midmid.step=mid.step+1;
            if(!book[midmid.x][midmid.y]&&mmap[midmid.x][midmid.y]=='.')
            {
                q.push(midmid);
            }
        }
    }
    sum[cnt]=ans;
}
int main()
{
    int n,m;
    cin >> n >>m;
    for(int i=0;i<=n+1;i++)
        for(int j=0;j<=m+1;j++)
            mmap[i][j]='*';
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            scanf(" %c",&mmap[i][j]);
        }
    }
    int cnt=1;
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            if(mmap[i][j]=='.')
            {
                if(!book[i][j])
                {
                    bfs(i,j,cnt++);
                }
            }
        }
    }
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            if(mmap[i][j]=='.')
                printf(".");
            else
            {
                int ansum=0;
                xjy mid;
                mid.x=i;
                mid.y=j;

                sset.clear();
                for(int k=0;k<4;k++)
                {
                    xjy midmid;
                    midmid.x=mid.x+dir[k][0];
                    midmid.y=mid.y+dir[k][1];
                    sset.insert(book[midmid.x][midmid.y]);
                }
                for(it=sset.begin();it!=sset.end();it++)
                {
                    ansum+=sum[*it];
                }
                printf("%d",(ansum+1)%10);
            }
        }
        printf("\n");
    }
}


#include<cstdio>
#include<iostream>
#include<queue>
#include<cstring>
#include<stack>
using namespace std;
int n,m;
struct node{
	int x,y;

}te;
char p[1005][1005];
int ans[1001][1001],col[1001][1001],sum[1001],book[1001];
node dot[1000001];
int ne[4][2]={1,0,0,1,-1,0,0,-1};
void bfs(int x,int y,int c){

	int i,j,tx,ty;
	queue <node> q;
	te.x=x;te.y=y;
	q.push(te);
	while(!q.empty())
    {
		for(i=0;i<4;i++)
		{
			tx=q.front().x+ne[i][0];
            ty=q.front().y+ne[i][1];
			if(tx<0||ty<0||tx>=n||ty>=m)
                continue;
			if(p[tx][ty]=='.'&&!col[tx][ty])
			{
				col[tx][ty]=c;
				sum[c]++;
				te.x=tx;
                te.y=ty;
				q.push(te);
			}
		}
		q.pop();
	}
	return ;
}
int main(){
	int i,j,co=0,c,xx,xy;
	scanf("%d %d",&n,&m);
	getchar();
	for(i=0;i<n;i++)
    {
		for(j=0;j<m;j++)
		{
			scanf("%c",&p[i][j]);
			if(p[i][j]=='*')
			{
				dot[co].x=i;dot[co].y=j;
				co++;
			}
		}
		getchar();
	}

    c=1;
	for(i=0;i<n;i++)
	{
		for(j=0;j<m;j++)
        {
			if(p[i][j]=='.'&&!col[i][j])
			{
				col[i][j]=c;
				sum[c]=1;
				bfs(i,j,c);
			}
			c++;
		}
	}
//	for(int i=0;i<n;i++)
//    {
//        for(int j=0;j<m;j++)
//            printf("%d",sum[col[i][j]]);
//        printf("\n");
//    }
	for(i=0;i<n;i++)
	{
		for(j=0;j<m;j++)
        {
			if(p[i][j]=='*')
            {
				memset(book,0,sizeof(book));
				for(int k=0;k<4;k++)
				{
					xx=i+ne[k][0];xy=j+ne[k][1];
					if(xx<0||xy<0||xx>=n||xy>=m)continue;
					if(!book[col[xx][xy]])
					{
						ans[i][j]+=sum[col[xx][xy]];
						book[col[xx][xy]]=1;
					}
				}
				ans[i][j]++;
			}
		}
	}
	for(i=0;i<n;i++)
    {
		for(j=0;j<m;j++)
		{
			if(p[i][j]=='*')
			cout<<(ans[i][j]%10);
			else
			cout<<p[i][j];
		}
		cout<<endl;
	}
	return 0;
}


#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
void init(int n);
int getf(int u);
void merge(int u,int v);
int bfs(int x,int y);
struct node{
	int x,y;
} q[1005*1005];
int f[1005*1005];
int num[1005*1005];
int r,c;
char a[1005][1005];
int book[1005][1005];
int nexts[4][2]={{0,1},{0,-1},{1,0},{-1,0}};

int slove(int x,int y)
{
	int ans=1;
	int t[4]={-1,-1,-1,-1};
	for(int i=0;i<4;i++)
	{
		int tx,ty;
		tx=x+nexts[i][0];
		ty=y+nexts[i][1];
		if(tx<0||ty<0||tx>=r||ty>=c)
			continue;
		if(a[tx][ty]=='.')
		{
			int flag=0;
			t[i]=getf(tx*c+ty);
			for(int j=0;j<i;j++)
				if(t[i]==t[j])
					flag=1;
			if(!flag)
				ans+=num[getf(tx*c+ty)];
		}
	}
	return ans%10;
}

int main()
{
	cin>>r>>c;
	for(int i=0;i<r;i++)
		for(int j=0;j<c;j++)
			cin>>a[i][j];
	init(r*c);
	for(int i=0;i<r;i++)
		for(int j=0;j<c;j++)
			if(a[i][j]=='.')
				if(!num[getf(i*c+j)])
					bfs(i,j);
	for(int i=0;i<r;i++)
	{
		for(int j=0;j<c;j++)
		{
			if(a[i][j]=='*')
				cout<<slove(i,j);
			else
				cout<<a[i][j];
		}
		cout<<endl;
	}
	return 0;
}

int bfs(int x,int y)
{
	memset(book,0,sizeof(book));
	int head=0,tail=0;
	q[tail].x=x;
	q[tail++].y=y;
	book[x][y]=1;
	while(head<tail)
	{
		for(int i=0;i<4;i++)
		{
			int tx,ty;
			tx=q[head].x+nexts[i][0];
			ty=q[head].y+nexts[i][1];
			if(tx<0||ty<0||tx>=r||ty>=c)
				continue;
			if(book[tx][ty]||a[tx][ty]!='.')
				continue;
			q[tail].x=tx;
			q[tail++].y=ty;
			book[tx][ty]=1;
			merge(x*c+y,tx*c+ty);
		}
		head++;
	}
	num[getf(x*c+y)]=tail%10;
	return tail%10;
}

void init(int n)
{
	for(int i=0;i<=n+5;i++)
		f[i]=i,num[i]=0;
}

int getf(int u)
{
	return f[u]==u?u:f[u]=getf(f[u]);
}

void merge(int u,int v)
{
	int t1=getf(u),t2=getf(v);
	if(t1!=t2)
		f[t2]=t1;
}


#include<bits/stdc++.h>
using namespace std;
int dir[4][2]={0,1,1,0,0,-1,-1,0};
char mmap[1111][1111];
int book[1111][1111];
struct xjy
{
    int x;
    int y;
    int step;
    bool operator < (const xjy &r)const
    {
        return step>r.step;
    }
};
int sum[11111111];
void bfs(int x,int y,int cnt)
{
    xjy mid;
    mid.x=x;
    mid.y=y;
    mid.step=0;
    priority_queue<xjy> q;
    q.push(mid);
    int ans=0;
    while(!q.empty())
    {
        mid=q.top();
        q.pop();
        if(book[mid.x][mid.y])
            continue;
        book[mid.x][mid.y]=cnt;
        ans++;
        xjy midmid;
        for(int i=0;i<4; i++)
        {
            midmid.x=mid.x+dir[i][0];
            midmid.y=mid.y+dir[i][1];
            midmid.step=mid.step+1;
            if(!book[midmid.x][midmid.y]&&mmap[midmid.x][midmid.y]=='.')
            {
                q.push(midmid);
            }
        }
    }
    sum[cnt]=ans;
}
int main()
{
    int n,m;
    cin >> n >>m;
    for(int i=0;i<=n+1;i++)
        for(int j=0;j<=m+1;j++)
            mmap[i][j]='*';
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            cin >> mmap[i][j];
        }
    }
    int cnt=1;
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            if(mmap[i][j]=='.')
            {
                if(!book[i][j])
                {
                    bfs(i,j,cnt++);
                }
            }
        }
    }
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            if(mmap[i][j]=='.')
                cout << ".";
            else
            {
                int ansum=0;
                xjy mid;
                mid.x=i;
                mid.y=j;
                int sset[5];
                int ccnt=0;
                for(int k=0;k<=4;k++)
                    sset[k]=0;
                for(int k=0;k<4;k++)
                {

                    xjy midmid;
                    midmid.x=mid.x+dir[k][0];
                    midmid.y=mid.y+dir[k][1];
                    int flag=1;
                    for(int kk=0;kk<4;kk++)
                        {
                            if(sset[kk]==book[midmid.x][midmid.y])
                                flag=0;
                        }
                    if(flag)
                        sset[ccnt++]=book[midmid.x][midmid.y];
                }
                for(int k=0;k<ccnt;k++)
                {
                    ansum+=sum[sset[k]];
                }
                cout << (ansum+1)%10;
            }
        }
        cout <<endl;
    }
}


//
//  main.cpp
//  the labyrinth
//
//  Created by Vivek Pratap Deo on 15/08/18.
//  Copyright © 2018 Vivek Pratap Deo. All rights reserved.
//
#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <set>
using namespace std;
int n,m;
char ans2[1005][1005];
char a[1005][1005];
int inrange(int x,int y)
{
    if(x>=0&&x<n&&y>=0&&y<m)
        return 1;
    return 0;
}
int dirx[]={1,-1,0,0};
int diry[]={0,0,1,-1};
int num[1005][1005];
int sz[1000006];
int tt=0;
void dfs(int i,int j)
{
   // cout<<i<<j<<"v"<<" ";
    sz[tt]++;
    num[i][j]=tt;
    for(int k=0;k<4;k++)
    {
        int x=i+dirx[k];
        int y=j+diry[k];
        if(inrange(x, y))
        {
        if(num[x][y]!=-1||a[x][y]=='*')
            continue;
        dfs(x, y);
        }
    }
}
int main(int argc, const char * argv[]) {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    //scanf("%d %d",&n,&m);
    cin>>n>>m;
   // cout<<n<<m;
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
//            cin>>ws;
//            scanf("%c",&a[i][j]);
            cin>>a[i][j];
        }
    }

//    for(int i=0;i<n;i++)
//    {
//        for(int j=0;j<m;j++)
//        {
//            cout<<a[i][j];
//        }
//        cout<<endl;
//    }
    memset(num, -1, sizeof(num));
   // cout<<a[0][1]<<" ";
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {

            if(num[i][j]==-1&&a[i][j]=='.')
            {
              //  cout<<i<<j<<"i"<<endl;
                dfs(i, j);
                tt++;
              //  cout<<tt<<" ";
            }
        }
    }
//    for(int i=0;i<n;i++)
//    {
//        for(int j=0;j<m;j++)
//        {
//            if(num[i][j]!=-1)
//            {
//                num[i][j]=sz[num[i][j]];
//            }
//        }
//    }
   int ans[1005][1005];

    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            if(a[i][j]=='*')
            {
                 set<int> s;
                 set<int>::iterator it;
                for(int k=0;k<4;k++)
                {
                    int x=i+dirx[k];
                    int y=j+diry[k];
                    if(inrange(x, y)&&a[x][y]=='.')
                        s.insert(num[x][y]);
                }
                for(it=s.begin();it!=s.end();it++)
                {
                    ans[i][j]+=sz[*it];
                }
                ans[i][j]+=1;
                ans2[i][j]=char('0'+ans[i][j]%10);
            }
            else
                ans2[i][j]='.';
        }
    }
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
                cout<<ans2[i][j];
        }
        cout<<endl;
    }
}


//
//  main.cpp
//  the labyrinth
//
//  Created by Vivek Pratap Deo on 15/08/18.
//  Copyright © 2018 Vivek Pratap Deo. All rights reserved.
//
#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <set>
using namespace std;
int n,m;
char a[1005][1005];
int inrange(int x,int y)
{
    if(x>=0&&x<n&&y>=0&&y<m)
        return 1;
    return 0;
}
int dirx[]={1,-1,0,0};
int diry[]={0,0,1,-1};
int num[1005][1005];
int sz[1000006];
int tt=0;
void dfs(int i,int j)
{
   // cout<<i<<j<<"v"<<" ";
    sz[tt]++;
    num[i][j]=tt;
    for(int k=0;k<4;k++)
    {
        int x=i+dirx[k];
        int y=j+diry[k];
        if(inrange(x, y))
        {
        if(num[x][y]!=-1||a[x][y]=='*')
            continue;
        dfs(x, y);
        }
    }
}
int main(int argc, const char * argv[]) {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    scanf("%d %d",&n,&m);
   // cout<<n<<m;
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            cin>>ws;
            scanf("%c",&a[i][j]);
        }
    }

//    for(int i=0;i<n;i++)
//    {
//        for(int j=0;j<m;j++)
//        {
//            cout<<a[i][j];
//        }
//        cout<<endl;
//    }
    memset(num, -1, sizeof(num));
   // cout<<a[0][1]<<" ";
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {

            if(num[i][j]==-1&&a[i][j]=='.')
            {
              //  cout<<i<<j<<"i"<<endl;
                dfs(i, j);
                tt++;
              //  cout<<tt<<" ";
            }
        }
    }
//    for(int i=0;i<n;i++)
//    {
//        for(int j=0;j<m;j++)
//        {
//            if(num[i][j]!=-1)
//            {
//                num[i][j]=sz[num[i][j]];
//            }
//        }
//    }
   int ans[1005][1005];

    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            if(a[i][j]=='*')
            {
                 set<int> s;
                 set<int>::iterator it;
                for(int k=0;k<4;k++)
                {
                    int x=i+dirx[k];
                    int y=j+diry[k];
                    if(inrange(x, y)&&a[x][y]=='.')
                        s.insert(num[x][y]);
                }
                for(it=s.begin();it!=s.end();it++)
                {
                    ans[i][j]+=sz[*it];
                }
                ans[i][j]+=1;
            }
//            else
//                ans[i][j]='.';
        }
    }
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            if(ans[i][j]==0)
            {
                cout<<'.';
            }
            else
            {
                cout<<ans[i][j];
            }
        }
        cout<<endl;
    }
}


//
//  main.cpp
//  the labyrinth
//
//  Created by Vivek Pratap Deo on 15/08/18.
//  Copyright © 2018 Vivek Pratap Deo. All rights reserved.
//

#include <iostream>
#include <vector>
#include <set>
using namespace std;
int n,m;
char a[1005][1005];
int inrange(int x,int y)
{
    if(x>=0&&x<n&&y>=0&&y<m)
        return 1;
    return 0;
}
int dirx[]={1,-1,0,0};
int diry[]={0,0,1,-1};
int num[1005][1005];
int sz[1000006];
int tt=0;
void dfs(int i,int j)
{
   // cout<<i<<j<<"v"<<" ";
    sz[tt]++;
    num[i][j]=tt;
    for(int k=0;k<4;k++)
    {
        int x=i+dirx[k];
        int y=j+diry[k];
        if(inrange(x, y))
        {
        if(num[x][y]!=-1||a[x][y]=='*')
            continue;
        dfs(x, y);
        }
    }
}
int main(int argc, const char * argv[]) {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    //scanf("%d %d",&n,&m);
    cin>>n>>m;
   // cout<<n<<m;
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
//            cin>>ws;
//            scanf("%c",&a[i][j]);
            cin>>a[i][j];
        }
    }

//    for(int i=0;i<n;i++)
//    {
//        for(int j=0;j<m;j++)
//        {
//            cout<<a[i][j];
//        }
//        cout<<endl;
//    }
    memset(num, -1, sizeof(num));
   // cout<<a[0][1]<<" ";
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {

            if(num[i][j]==-1&&a[i][j]=='.')
            {
              //  cout<<i<<j<<"i"<<endl;
                dfs(i, j);
                tt++;
              //  cout<<tt<<" ";
            }
        }
    }
//    for(int i=0;i<n;i++)
//    {
//        for(int j=0;j<m;j++)
//        {
//            if(num[i][j]!=-1)
//            {
//                num[i][j]=sz[num[i][j]];
//            }
//        }
//    }
   int ans[1005][1005];

    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            if(a[i][j]=='*')
            {
                 set<int> s;
                 set<int>::iterator it;
                for(int k=0;k<4;k++)
                {
                    int x=i+dirx[k];
                    int y=j+diry[k];
                    if(inrange(x, y)&&a[x][y]=='.')
                        s.insert(num[x][y]);
                }
                for(it=s.begin();it!=s.end();it++)
                {
                    ans[i][j]+=sz[*it];
                }
                ans[i][j]+=1;
            }
//            else
//                ans[i][j]='.';
        }
    }
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            if(ans[i][j]==0)
            {
                cout<<'.';
            }
            else
            {
                cout<<ans[i][j];
            }
        }
        cout<<endl;
    }
}


//
//  main.cpp
//  the labyrinth
//
//  Created by Vivek Pratap Deo on 15/08/18.
//  Copyright © 2018 Vivek Pratap Deo. All rights reserved.
//
#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <set>
using namespace std;
int n,m;
char a[1005][1005];
int inrange(int x,int y)
{
    if(x>=0&&x<n&&y>=0&&y<m)
        return 1;
    return 0;
}
int dirx[]={1,-1,0,0};
int diry[]={0,0,1,-1};
int num[1005][1005];
int sz[1000006];
int tt=0;
void dfs(int i,int j)
{
   // cout<<i<<j<<"v"<<" ";
    sz[tt]++;
    num[i][j]=tt;
    for(int k=0;k<4;k++)
    {
        int x=i+dirx[k];
        int y=j+diry[k];
        if(inrange(x, y))
        {
        if(num[x][y]!=-1||a[x][y]=='*')
            continue;
        dfs(x, y);
        }
    }
}
int main(int argc, const char * argv[]) {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    //scanf("%d %d",&n,&m);
    cin>>n>>m;
   // cout<<n<<m;
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
//            cin>>ws;
//            scanf("%c",&a[i][j]);
            cin>>a[i][j];
        }
    }

//    for(int i=0;i<n;i++)
//    {
//        for(int j=0;j<m;j++)
//        {
//            cout<<a[i][j];
//        }
//        cout<<endl;
//    }
    memset(num, -1, sizeof(num));
   // cout<<a[0][1]<<" ";
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {

            if(num[i][j]==-1&&a[i][j]=='.')
            {
              //  cout<<i<<j<<"i"<<endl;
                dfs(i, j);
                tt++;
              //  cout<<tt<<" ";
            }
        }
    }
//    for(int i=0;i<n;i++)
//    {
//        for(int j=0;j<m;j++)
//        {
//            if(num[i][j]!=-1)
//            {
//                num[i][j]=sz[num[i][j]];
//            }
//        }
//    }
   int ans[1005][1005];

    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            if(a[i][j]=='*')
            {
                 set<int> s;
                 set<int>::iterator it;
                for(int k=0;k<4;k++)
                {
                    int x=i+dirx[k];
                    int y=j+diry[k];
                    if(inrange(x, y)&&a[x][y]=='.')
                        s.insert(num[x][y]);
                }
                for(it=s.begin();it!=s.end();it++)
                {
                    ans[i][j]+=sz[*it];
                }
                ans[i][j]+=1;
                ans[i][j]%=10;
            }
//            else
//                ans[i][j]='.';
        }
    }
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            if(ans[i][j]==0)
            {
                cout<<'.';
            }
            else
            {
                cout<<ans[i][j];
            }
        }
        cout<<endl;
    }
}


//
//  main.cpp
//  the labyrinth
//
//  Created by Vivek Pratap Deo on 15/08/18.
//  Copyright © 2018 Vivek Pratap Deo. All rights reserved.
//
#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <set>
using namespace std;
int n,m;
char a[1005][1005];
int inrange(int x,int y)
{
    if(x>=0&&x<n&&y>=0&&y<m)
        return 1;
    return 0;
}
int dirx[]={1,-1,0,0};
int diry[]={0,0,1,-1};
int num[1005][1005];
int sz[1000006];
int tt=0;
void dfs(int i,int j)
{
   // cout<<i<<j<<"v"<<" ";
    sz[tt]++;
    num[i][j]=tt;
    for(int k=0;k<4;k++)
    {
        int x=i+dirx[k];
        int y=j+diry[k];
        if(inrange(x, y))
        {
        if(num[x][y]!=-1||a[x][y]=='*')
            continue;
        dfs(x, y);
        }
    }
}
int main(int argc, const char * argv[]) {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    //scanf("%d %d",&n,&m);
    cin>>n>>m;
   // cout<<n<<m;
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
//            cin>>ws;
//            scanf("%c",&a[i][j]);
            cin>>a[i][j];
        }
    }

//    for(int i=0;i<n;i++)
//    {
//        for(int j=0;j<m;j++)
//        {
//            cout<<a[i][j];
//        }
//        cout<<endl;
//    }
    memset(num, -1, sizeof(num));
   // cout<<a[0][1]<<" ";
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {

            if(num[i][j]==-1&&a[i][j]=='.')
            {
              //  cout<<i<<j<<"i"<<endl;
                dfs(i, j);
                tt++;
              //  cout<<tt<<" ";
            }
        }
    }
//    for(int i=0;i<n;i++)
//    {
//        for(int j=0;j<m;j++)
//        {
//            if(num[i][j]!=-1)
//            {
//                num[i][j]=sz[num[i][j]];
//            }
//        }
//    }
   int ans[1005][1005];

    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            if(a[i][j]=='*')
            {
                 set<int> s;
                 set<int>::iterator it;
                for(int k=0;k<4;k++)
                {
                    int x=i+dirx[k];
                    int y=j+diry[k];
                    if(inrange(x, y)&&a[x][y]=='.')
                        s.insert(num[x][y]);
                }
                for(it=s.begin();it!=s.end();it++)
                {
                    ans[i][j]+=sz[*it];
                }
                ans[i][j]+=1;
            }
//            else
//                ans[i][j]='.';
        }
    }
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            if(ans[i][j]==0)
            {
                cout<<'.';
            }
            else
            {
                cout<<ans[i][j];
            }
        }
        cout<<endl;
    }
}


#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define ll long long int
#define ssd ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define mod 1000000007
#define ordered_set tree<ll, null_type, less_equal<ll>, rb_tree_tag,tree_order_statistics_node_update>
#define trace(x) cerr<<#x<<" : "<<x<<endl;
using namespace std;
using namespace __gnu_pbds;

char arr[1001][1001];
bool visited[1001][1001]={};
int grp[1001][1001]={};
int val[1001]={};
int n,m,kk=0,c=0;
void func(int a,int b)
{
    kk++;
    grp[a][b]=c;
    visited[a][b]=1;
    if(a+1<=n && arr[a+1][b]=='.' && !visited[a+1][b]) func(a+1,b);
    if(a-1>=1 && arr[a-1][b]=='.' && !visited[a-1][b]) func(a-1,b);
    if(b+1<=m && arr[a][b+1]=='.' && !visited[a][b+1]) func(a,b+1);
    if(b-1>=1 && arr[a][b-1]=='.' && !visited[a][b-1]) func(a,b-1);
}

int main()
{
    ssd
    cin>>n>>m;
    int i,j,k;
    for(i=1;i<=n;i++)
    {
        for(j=1;j<=m;j++)
        {
            cin>>arr[i][j];
        }
    }
    for(i=1;i<=n;i++)
    {
        for(j=1;j<=m;j++)
        {
            if(arr[i][j]=='.' && !visited[i][j])
            {
                c++;
                kk=0;
                func(i,j);
                val[c]=kk;
            }
        }
    }
    for(i=1;i<=n;i++)
    {
        for(j=1;j<=m;j++)
        {
            if(arr[i][j]=='.') cout<<".";
            else
            {
                set<int> s;
                int ans=0;
                if(i-1>=1) s.insert(grp[i-1][j]);
                if(i+1<=n) s.insert(grp[i+1][j]);
                if(j-1>=1) s.insert(grp[i][j-1]);
                if(j+1<=m) s.insert(grp[i][j+1]);
                for(auto it:s) ans+=val[it];
                cout<<(ans+1)%10;
            }
        }
        cout<<endl;
    }
	return 0;
}


#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define ll long long int
#define ssd ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define mod 1000000007
#define ordered_set tree<ll, null_type, less_equal<ll>, rb_tree_tag,tree_order_statistics_node_update>
#define trace(x) cerr<<#x<<" : "<<x<<endl;
using namespace std;
using namespace __gnu_pbds;

char arr[1001][1001];
bool visited[1001][1001]={};
int grp[1001][1001]={};
int val[1001]={};
int n,m,kk=0,c=0;
void func(int a,int b)
{
    kk++;
    grp[a][b]=c;
    visited[a][b]=1;
    if(a+1<=n && arr[a+1][b]=='.' && !visited[a+1][b]) func(a+1,b);
    if(a-1>=1 && arr[a-1][b]=='.' && !visited[a-1][b]) func(a-1,b);
    if(b+1<=m && arr[a][b+1]=='.' && !visited[a][b+1]) func(a,b+1);
    if(b-1>=1 && arr[a][b-1]=='.' && !visited[a][b-1]) func(a,b-1);
}

int main()
{
    ssd
    cin>>n>>m;
    int i,j,k;
    for(i=1;i<=n;i++)
    {
        for(j=1;j<=m;j++)
        {
            cin>>arr[i][j];
        }
    }
    for(i=1;i<=n;i++)
    {
        for(j=1;j<=m;j++)
        {
            if(arr[i][j]=='.' && !visited[i][j])
            {
                c++;
                kk=0;
                func(i,j);
                val[c]=kk;
            }
        }
    }
    for(i=1;i<=n;i++)
    {
        for(j=1;j<=m;j++)
        {
            if(arr[i][j]=='.') cout<<".";
            else
            {
                set<int> s;
                int ans=0;
                if(i-1>=1) s.insert(grp[i-1][j]);
                if(i+1<=n) s.insert(grp[i+1][j]);
                if(j-1>=1) s.insert(grp[i][j-1]);
                if(j+1<=m) s.insert(grp[i][j+1]);
                for(auto it:s) ans+=val[it];
                cout<<ans+1;
            }
        }
        cout<<endl;
    }
	return 0;
}


#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define ll long long int
#define ssd ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define mod 1000000007
#define ordered_set tree<ll, null_type, less_equal<ll>, rb_tree_tag,tree_order_statistics_node_update>
#define trace(x) cerr<<#x<<" : "<<x<<endl;
using namespace std;
using namespace __gnu_pbds;

char arr[1005][1005];
bool visited[1005][1005]={};
int grp[1005][1005]={};
int val[1000005]={};
int n,m,kk=0,c=0;
void func(int a,int b)
{
    if(a>n||b>m||a<1||b<1) return;
    if(visited[a][b] || arr[a][b]=='*') return;
    kk++;
    grp[a][b]=c;
    visited[a][b]=1;
    func(a+1,b);
    func(a-1,b);
    func(a,b+1);
    func(a,b-1);
}

int main()
{
    ssd
    cin>>n>>m;
    int i,j,k;
    for(i=1;i<=n;i++)
    {
        for(j=1;j<=m;j++)
        {
            cin>>arr[i][j];
        }
    }
    for(i=1;i<=n;i++)
    {
        for(j=1;j<=m;j++)
        {
            if(arr[i][j]=='.' && !visited[i][j])
            {
                c++;
                kk=0;
                func(i,j);
                val[c]=kk;
            }
        }
    }
    for(i=1;i<=n;i++)
    {
        for(j=1;j<=m;j++)
        {
            if(arr[i][j]=='.') cout<<".";
            else
            {
                set<int> s;
                int ans=0;
                if(i-1>=1) s.insert(grp[i-1][j]);
                if(i+1<=n) s.insert(grp[i+1][j]);
                if(j-1>=1) s.insert(grp[i][j-1]);
                if(j+1<=m) s.insert(grp[i][j+1]);
                for(auto it:s) ans+=val[it];
                cout<<(ans+1)%10;
            }
        }
        cout<<endl;
    }
	return 0;
}


#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define ll long long int
#define ssd ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define mod 1000000007
#define ordered_set tree<ll, null_type, less_equal<ll>, rb_tree_tag,tree_order_statistics_node_update>
#define trace(x) cerr<<#x<<" : "<<x<<endl;
using namespace std;
using namespace __gnu_pbds;

char arr[1001][1001];
bool visited[1001][1001]={};
int grp[1001][1001]={};
int val[1001]={};
int n,m,kk=0,c=0;
void func(int a,int b)
{
    kk++;
    grp[a][b]=c;
    visited[a][b]=1;
    if(a+1<=n && arr[a+1][b]=='.' && !visited[a+1][b]) func(a+1,b);
    if(a-1>=1 && arr[a-1][b]=='.' && !visited[a-1][b]) func(a-1,b);
    if(b+1<=m && arr[a][b+1]=='.' && !visited[a][b+1]) func(a,b+1);
    if(b-1>=1 && arr[a][b-1]=='.' && !visited[a][b-1]) func(a,b-1);
}

int main()
{
    ssd
    cin>>n>>m;
    int i,j,k;
    for(i=1;i<=n;i++)
    {
        for(j=1;j<=m;j++)
        {
            cin>>arr[i][j];
        }
    }
    for(i=1;i<=n;i++)
    {
        for(j=1;j<=m;j++)
        {
            if(arr[i][j]=='.' && !visited[i][j])
            {
                c++;
                kk=0;
                func(i,j);
                val[c]=kk;
            }
        }
    }
    for(i=1;i<=n;i++)
    {
        for(j=1;j<=m;j++)
        {
            if(arr[i][j]=='.') cout<<".";
            else
            {
                set<int> s;
                int ans=0;
                if(i-1>=1 && arr[i-1][j]=='.') s.insert(grp[i-1][j]);
                if(i+1<=n && arr[i+1][j]=='.') s.insert(grp[i+1][j]);
                if(j-1>=1 && arr[i][j-1]=='.') s.insert(grp[i][j-1]);
                if(j+1<=m && arr[i][j+1]=='.') s.insert(grp[i][j+1]);
                for(auto it:s) ans+=val[it];
                cout<<(ans+1)%10;
            }
        }
        cout<<endl;
    }
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int n,m;
int ans;
char a[1002][1002];
int visit[1002][1002];
int dir[4][2]={0,1,0,-1,1,0,-1,0};
void dfs(int x,int y)
{
    if(a[x][y]=='*')
        return;
    if(visit[x][y])
        return;
    if(x<0||x>=n||y<0||y>=m)
        return;
    if(a[x][y]=='.')
    {
         ans++;visit[x][y]=1;
    }
    for(int i=0;i<4;i++)
    {
        int tx=x+dir[i][0];
        int ty=y+dir[i][1];

        dfs(tx,ty);

    }
}
void dfs2(int x,int y)
{
    if(x<0||x>=n||y<0||y>=m)
        return;
    if(!visit[x][y])
        return;
    if(visit[x][y])
    {
        visit[x][y]=0;
    }
    for(int i=0;i<4;i++)
    {

        int tx=x+dir[i][0];
        int ty=y+dir[i][1];

        dfs2(tx,ty);
    }

}
int main()
{
    scanf("%d%d",&n,&m);
    for(int i=0;i<n;i++)
        scanf("%s",a[i]);
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            if(a[i][j]=='.')
                printf(".");
            else
            {
                ans=0;
                a[i][j]='.';
                dfs(i,j);dfs2(i,j);
                printf("%d",ans%10);
                a[i][j]='*';
            }

        }printf("\n");
    }
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
int n,m,ans;
char a[1002][1002];
int visit[1000][1000];
int dir[4][2]={0,1,0,-1,1,0,-1,0};
void dfs(int x,int y)
{
    if(a[x][y]=='*')
        return;
    if(visit[x][y])
        return;
    if(x<0||x>=n||y<0||y>=m)
        return;
    if(a[x][y]=='.')
    {
         ans++;visit[x][y]=1;
    }
    for(int i=0;i<4;i++)
    {
        int tx=x+dir[i][0];
        int ty=y+dir[i][1];
        dfs(tx,ty);
    }
}
int main()
{
    scanf("%d%d",&n,&m);
    for(int i=0;i<n;i++)
        scanf("%s",a[i]);
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            if(a[i][j]=='.')
                printf(".");
            else
            {
                ans=0;memset(visit,0,sizeof(visit));
                a[i][j]='.';
                dfs(i,j);
                printf("%d",ans);
                a[i][j]='*';
            }

        }printf("\n");
    }
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
int n,m,ans;
char a[1002][1002];
int visit[1002][1002];
int dir[4][2]={0,1,0,-1,1,0,-1,0};
void dfs(int x,int y)
{
    if(a[x][y]=='*')
        return;
    if(visit[x][y])
        return;
    if(x<0||x>=n||y<0||y>=m)
        return;
    if(a[x][y]=='.')
    {
         ans++;visit[x][y]=1;
    }
    for(int i=0;i<4;i++)
    {
        int tx=x+dir[i][0];
        int ty=y+dir[i][1];
        dfs(tx,ty);
    }
}
int main()
{
    scanf("%d%d",&n,&m);
    for(int i=0;i<n;i++)
        scanf("%s",a[i]);
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            if(a[i][j]=='.')
                printf(".");
            else
            {
                ans=0;memset(visit,0,sizeof(visit));
                a[i][j]='.';
                dfs(i,j);
                printf("%d",ans);
                a[i][j]='*';
            }

        }printf("\n");
    }
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int n,m;
int ans;
char a[1002][1002];
int visit[1002][1002];
int dir[4][2]={0,1,0,-1,1,0,-1,0};
void dfs(int x,int y)
{
    if(a[x][y]=='*')
        return;
    if(visit[x][y])
        return;
    if(x<0||x>=n||y<0||y>=m)
        return;
    if(a[x][y]=='.')
    {
         ans++;visit[x][y]=1;
    }
    for(int i=0;i<4;i++)
    {
        int tx=x+dir[i][0];
        int ty=y+dir[i][1];
        dfs(tx,ty);
    }
}
int main()
{
    scanf("%d%d",&n,&m);
    for(int i=0;i<n;i++)
        scanf("%s",a[i]);
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            if(a[i][j]=='.')
                printf(".");
            else
            {
                ans=0;memset(visit,0,sizeof(visit));
                a[i][j]='.';
                dfs(i,j);
                printf("%d",ans%10);
                a[i][j]='*';
            }

        }printf("\n");
    }
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int n,m;
int cnt;
const int MAXN=1e6+5;
char a[1002][1002];
int visit[1002][1002],book[MAXN];
int dir[4][2]={0,1,0,-1,1,0,-1,0};
void dfs(int x,int y)
{
    if(a[x][y]=='*')
        return;
    if(visit[x][y])
        return;
    if(x<0||x>=n||y<0||y>=m)
        return;
    visit[x][y]=cnt;book[cnt]++;
    for(int i=0;i<4;i++)
    {
        int tx=x+dir[i][0];
        int ty=y+dir[i][1];
        dfs(tx,ty);

    }
}
int main()
{
    scanf("%d%d",&n,&m);
    for(int i=0;i<n;i++)
        scanf("%s",a[i]);
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            if(a[i][j]=='.'&&!visit[i][j])
            {
                cnt++;dfs(i,j);
            }
        }
    }
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            if(a[i][j]=='*')
            {
                int ans=1;
                set<int>s;set<int>::iterator it;
                for(int k=0;k<4;k++)
                {
                    int tx=i+dir[k][0];
                    int ty=j+dir[k][1];
                    if(a[tx][ty]=='.'&&tx>=0&&tx<n&&ty>=0&&ty<m)
                        s.insert(visit[tx][ty]);
                }
                for(it=s.begin();it!=s.end();it++)
                {
                    ans+=book[*it];

                }printf("%d",ans);
            }
            else
                printf(".");

        }printf("\n");
    }
    return 0;
}


using System;
class CFR123D2A
{
	static void Main()
	{
		int n = int.Parse(Console.ReadLine());
		ReadAndPrintMsg(n);
	}

	static void ReadAndPrintMsg(int n)
	{
		bool throwOperatorFound = false;
		int insertedTryBlockCount = 0;
		string exceptionType = "";
		for (int i = 0; i < n; i++)
		{
			string line = Console.ReadLine();
			int tryIndex = line.IndexOf("try");
			int catchIndex = line.IndexOf("catch");
			int throwIndex = line.IndexOf("throw");
			if ( (tryIndex != -1) &&
					((catchIndex == -1) && (throwIndex == -1) ||
					((catchIndex != -1) && (tryIndex < catchIndex)) ||
					((throwIndex != -1) && (tryIndex < throwIndex))) )
			{
				if (throwOperatorFound == true)
				{
					insertedTryBlockCount++;
				}
			}
			else if ( (catchIndex != -1) &&
						((throwIndex == -1) ||
						((throwIndex != -1) && (catchIndex < throwIndex))) )
			{
				if (throwOperatorFound == true)
				{
					if (insertedTryBlockCount > 0)
					{
						insertedTryBlockCount--;
					}
					else
					{
						string catchExceptionType = "";
						int startIndex = line.IndexOf("(") + 1;
						int length = line.IndexOf(",") - startIndex;
						catchExceptionType = line.Substring(startIndex, length).Replace(" ", "");

						if (String.Compare(catchExceptionType, exceptionType) == 0)
						{
							string catchMessage = "";
							startIndex = line.IndexOf("\"") + 1;
							length = line.LastIndexOf("\"") - startIndex;
							catchMessage = line.Substring(startIndex, length).TrimStart(' ').TrimEnd(' ');

							Console.WriteLine(catchMessage);
							return;
						}
					}
				}
			}
			else if (throwIndex != -1)
			{
				throwOperatorFound = true;
				int startIndex = line.IndexOf("(") + 1;
				int length = line.IndexOf(")") - startIndex;
				exceptionType = line.Substring(startIndex, length).Replace(" ", "");
			}
		}
		Console.WriteLine("Unhandled Exception");
	}
}


using System;
class CFR123D2A
{
	static void Main()
	{
		int n = int.Parse(Console.ReadLine());
		ReadAndPrintMsg(n);
		//Console.ReadKey();
	}

	static void ReadAndPrintMsg(int n)
	{
		bool throwOperatorFound = false;
		int insertedTryBlockCount = 0;
		string exceptionType = "";
		for (int i = 0; i < n; i++)
		{
			string line = Console.ReadLine();
			if (line.IndexOf("try") != -1)
			{
				if (throwOperatorFound == true)
				{
					insertedTryBlockCount++;
				}
			}
			else if (line.IndexOf("catch") != -1)
			{
				if (throwOperatorFound == true)
				{
					if (insertedTryBlockCount > 0)
					{
						insertedTryBlockCount--;
					}
					else
					{
						string catchExceptionType = "";
						int startIndex = line.IndexOf("(") + 1;
						int length = line.IndexOf(",") - startIndex;
						catchExceptionType = line.Substring(startIndex, length).Replace(" ", "");

						if (String.Compare(catchExceptionType, exceptionType) == 0)
						{
							string catchMessage = "";
							startIndex = line.IndexOf("\"") + 1;
							length = line.LastIndexOf("\"") - startIndex;
							catchMessage = line.Substring(startIndex, length).TrimStart(' ').TrimEnd(' ');

							Console.WriteLine(catchMessage);
							return;
						}
					}
				}
			}
			else if (line.IndexOf("throw") != -1)
			{
				throwOperatorFound = true;
				int startIndex = line.IndexOf("(") + 1;
				int length = line.IndexOf(")") - startIndex;
				exceptionType = line.Substring(startIndex, length).Replace(" ", "");
			}
		}
		Console.WriteLine("Unhandled Exception");
	}
}


using System;
class CFR123D2A
{
	static void Main()
	{
		int n = int.Parse(Console.ReadLine());
		ReadAndPrintMsg(n);
	}

	static void ReadAndPrintMsg(int n)
	{
		bool throwOperatorFound = false;
		int insertedTryBlockCount = 0;
		string exceptionType = "";
		for (int i = 0; i < n; i++)
		{
			string line = Console.ReadLine().TrimStart(' ');

			if (String.IsNullOrWhiteSpace(line) == true) continue;
			else if (line[0] == 't' && line[1] == 'h')
			{
				throwOperatorFound = true;
				int startIndex = line.IndexOf("(") + 1;
				int length = line.IndexOf(")") - startIndex;
				exceptionType = line.Substring(startIndex, length).Replace(" ", "");
			}
			else if (throwOperatorFound == false) continue;
			else if (line[0] == 't')
			{
				insertedTryBlockCount++;
			}
			else if (line[0] == 'c')
			{
				if (insertedTryBlockCount > 0)
				{
					insertedTryBlockCount--;
				}
				else
				{
					string catchExceptionType = "";
					int startIndex = line.IndexOf("(") + 1;
					int length = line.IndexOf(",") - startIndex;
					catchExceptionType = line.Substring(startIndex, length).Replace(" ", "");

					if (String.Compare(catchExceptionType, exceptionType) == 0)
					{
						string catchMessage = "";
						startIndex = line.IndexOf("\"") + 1;
						length = line.LastIndexOf("\"") - startIndex;
						catchMessage = line.Substring(startIndex, length).TrimStart(' ').TrimEnd(' ');

						Console.WriteLine(catchMessage);
						return;
					}
				}
			}
		}
		Console.WriteLine("Unhandled Exception");
	}
}


using System;
class CFR123D2A
{
	static void Main()
	{
		int n = int.Parse(Console.ReadLine());
		ReadAndPrintMsg(n);
	}

	static void ReadAndPrintMsg(int n)
	{
		bool throwOperatorFound = false;
		int insertedTryBlockCount = 0;
		string exceptionType = "";
		for (int i = 0; i < n; i++)
		{
			string line = Console.ReadLine().TrimStart(' ');

			if (line.Length == 0) continue;
			else if (line[0] == 't' && line[1] == 'h')
			{
				throwOperatorFound = true;
				int startIndex = line.IndexOf("(") + 1;
				int length = line.IndexOf(")") - startIndex;
				exceptionType = line.Substring(startIndex, length).Replace(" ", "");
			}
			else if (throwOperatorFound == false) continue;
			else if (line[0] == 't')
			{
				insertedTryBlockCount++;
			}
			else if (line[0] == 'c')
			{
				if (insertedTryBlockCount > 0)
				{
					insertedTryBlockCount--;
				}
				else
				{
					string catchExceptionType = "";
					int startIndex = line.IndexOf("(") + 1;
					int length = line.IndexOf(",") - startIndex;
					catchExceptionType = line.Substring(startIndex, length).Replace(" ", "");

					if (String.Compare(catchExceptionType, exceptionType) == 0)
					{
						string catchMessage = "";
						startIndex = line.IndexOf("\"") + 1;
						length = line.LastIndexOf("\"") - startIndex;
						catchMessage = line.Substring(startIndex, length).TrimStart(' ').TrimEnd(' ');

						Console.WriteLine(catchMessage);
						return;
					}
				}
			}
		}
		Console.WriteLine("Unhandled Exception");
	}
}


using System;
class CFR123D2A
{
	static void Main()
	{
		int n = int.Parse(Console.ReadLine());
		ReadAndPrintMsg(n);
		//Console.ReadKey();
	}

	static void ReadAndPrintMsg(int n)
	{
		bool throwOperatorFound = false;
		int insertedTryBlockCount = 0;
		string exceptionType = "";
		for (int i = 0; i < n; i++)
		{
			string line = Console.ReadLine().TrimStart(' ');
			int tryIndex = line.IndexOf("try");
			int catchIndex = line.IndexOf("catch");
			int throwIndex = line.IndexOf("throw");

			if (throwIndex == 0)
			{
				throwOperatorFound = true;
				int startIndex = line.IndexOf("(") + 1;
				int length = line.IndexOf(")") - startIndex;
				exceptionType = line.Substring(startIndex, length).Replace(" ", "");
			}
			else if (throwOperatorFound == false) continue;
			else if (tryIndex == 0)
			{
				insertedTryBlockCount++;
			}
			else if (catchIndex == 0)
			{
				if (insertedTryBlockCount > 0)
				{
					insertedTryBlockCount--;
				}
				else
				{
					string catchExceptionType = "";
					int startIndex = line.IndexOf("(") + 1;
					int length = line.IndexOf(",") - startIndex;
					catchExceptionType = line.Substring(startIndex, length).Replace(" ", "");

					if (String.Compare(catchExceptionType, exceptionType) == 0)
					{
						string catchMessage = "";
						startIndex = line.IndexOf("\"") + 1;
						length = line.LastIndexOf("\"") - startIndex;
						catchMessage = line.Substring(startIndex, length).TrimStart(' ').TrimEnd(' ');

						Console.WriteLine(catchMessage);
						return;
					}
				}
			}
		}
		Console.WriteLine("Unhandled Exception");
	}
}


from sys import stdin
import re

def get(s):
    throw, error = '', ''
    be, en = s.find('('), s.find(')')

    while s[be] != ',':
        be += 1
        throw += s[be]

    while s[en] != ',':
        en -= 1
        if s[en] != '\"':
            error += s[en]

    return throw[:-1].strip(), error[:-1][::-1].strip()

rstr = lambda: stdin.readline().strip()
n = int(input())
a, ans, flag = [rstr() for _ in range(n)], 'Unhandled Exception', 0
stack, c = [], 0

for i in a:
    if not stack and flag:
        break

    if i == 'try':
        if flag:
            c += 1
        else:
            stack.append(i)

    elif 'throw' in i:
        flag = i[8:-2]

    elif 'catch' in i:
        if not flag:
            stack.pop()
        elif c:
            c -= 1
        else:
            stack.pop()
            throw, error = get(i)

            if throw == flag:
                ans = error
                break

print(ans)


from sys import stdin
import re

def get(s):
    throw, error = '', ''
    be, en = s.find('(') + 1, s.find(')') - 1

    while s[be] != ',':
        throw += s[be]
        be += 1

    while s[en] != ',':
        if s[en] != '\"':
            error += s[en]
        en -= 1

    return throw.strip(), error[::-1].strip()

def get_throw(s):
    be, throw = s.find('(') + 1, ''

    while s[be] != ')':
        throw += s[be]
        be += 1

    return throw.strip()

rstr = lambda: stdin.readline().strip()
n = int(input())
a, ans, flag = [rstr() for _ in range(n)], 'Unhandled Exception', 0
stack, c = [], 0

for i in a:
    if not stack and flag:
        break

    if i == 'try':
        if flag:
            c += 1
        else:
            stack.append(i)

    elif 'throw' in i:
        flag = get_throw(i)

    elif 'catch' in i:
        if not flag:
            stack.pop()
        elif c:
            c -= 1
        else:
            stack.pop()
            throw, error = get(i)
            # print(throw, error)
            if throw == flag:
                ans = error
                break

print(ans)


ii=lambda:int(input())
kk=lambda:map(int,input().split())
ll=lambda:list(kk())
opened=0
catchd = -1
typ = ""

for _ in range(ii()):
	s = input().strip()
	if s == "": continue
	if s == "try": opened+=1
	elif s[0] == 't':
		catchd = opened
		typ = s[5:-1].strip()[1:].strip()
		print(typ, len(typ))
	else:
		if catchd == opened:
			e,m,_ = s[5:].strip()[1:-1].strip().split("\"")
			e,_=e.split(",")
			e.strip()
			if e == typ:
				print(m)
				exit()
			catchd-=1
		opened-=1
print("Unhandled Exception")


ii=lambda:int(input())
kk=lambda:map(int,input().split())
ll=lambda:list(kk())
opened=0
catchd = -1
typ = ""

for _ in range(ii()):
	s = input().strip()
	if s == "": continue
	if s == "try": opened+=1
	elif s[0] == 't':
		catchd = opened
		typ = s[5:-1].strip()[1:].strip()
	else:
		if catchd == opened:
			e,m,_ = s[5:].strip()[1:-1].strip().split("\"")
			e,_=e.split(",")
			e=e.strip()
			if e == typ:
				print(m)
				exit()
			catchd-=1
		opened-=1
print("Unhandled Exception")


ii=lambda:int(input())
kk=lambda:map(int,input().split())
ll=lambda:list(kk())
opened=0
catchd = -1
typ = ""

for _ in range(ii()):
	s = input().strip()
	if s == "": continue
	if s == "try": opened+=1
	elif s[0] == 't':
		catchd = opened
		typ = s[5:-1].strip()[1:].strip()
	else:
		if catchd == opened:
			e,m,_ = s[5:].strip()[1:-1].strip().split("\"")
			e,_=e.split(",")
			e.strip()
			if e == typ:
				print(m)
				exit()
			catchd-=1
		opened-=1
print("Unhandled Exception")


import io, os
# input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
input = io.StringIO(os.read(0, os.fstat(0).st_size).decode()).readline
ii=lambda:int(input())
kk=lambda:map(int,input().split())
ll=lambda:list(kk())
opened=0
catchd = -1
typ = ""

for _ in range(ii()):
	s = input().strip()
	if s == "": continue
	if s == "try": opened+=1
	elif s[0] == 't':
		catchd = opened
		typ = s[5:-1].strip()[1:].strip()
	else:
		if catchd == opened:
			e,m,_ = s[5:].strip()[1:-1].strip().split("\"")
			e,_=e.split(",")
			e=e.strip()
			if e == typ:
				print(m)
				exit()
			catchd-=1
		opened-=1
print("Unhandled Exception")


#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
ALPHA='abcdefghijklmnopqrstuvwxyz'
M=1000000007
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]

#-------------------------code---------------------------#
# vsInput()

n=Int()

stack=[]
id=1

for _ in range(n):

    if(stack==[]):
        exception=-1
        ex_id=-1

    s=input().strip()
    if(s==''): continue

    if(s=='try'):
        stack.append(id)
        id+=1

    elif(s[1]=='h'):
        s=s[5:].strip().lstrip('(').rstrip(')').strip()

        if(len(stack)!=0):
            exception=s
            ex_id=stack[-1]
    else:

        s=s[5:].strip().lstrip('(').rstrip(')').strip()
        e,comment=s.split(',')
        e=e.strip()
        comment=comment.strip()

        comment=comment.lstrip('"').rstrip('"')

        # print(e,comment)

        last_id=stack.pop()
        if(last_id<=ex_id and e==exception):
            print(comment)
            exit()

    # print(stack)
    # print(s)

print("Unhandled Exception")


#from bisect import bisect_left as bl                #c++ lowerbound bl(array,element)
#from bisect import bisect_right as br               #c++ upperbound br(array,element)
#from __future__ import print_function, division    #while using python2

from collections import defaultdict
from collections import deque

def main():
    #sys.stdin = open('input.txt', 'r')
    #sys.stdout = open('output.txt', 'w')
    n = int(input())

    nodes = defaultdict(lambda : [])     # node_index: [parent ind, catch type, catch msg]
    cur = 0
    stack = [0]

    exception_node = -1
    error = ""
    for i in range(n):
        s = input().strip(' ')
        # print(s)
        if len(s) == 0:
            continue
        if s == "try":
            cur += 1
            stack.append(cur)
        elif s[:5] == "throw":
            exception_node = stack[-1]
            error = s[5:].split('(')[-1].strip(' ').strip(')').strip(' ')
        else:
            node = stack[-1]
            stack.pop()
            parent = stack[-1]
            a1, a2 = s[6:-1].split(',')
            nodes[node] = [parent, a1.strip(' ').strip('(').strip(' '), a2.strip(' ').strip('"')]
    # print(dict(nodes))
    # print(error, exception_node)

    cur = exception_node
    while True:
        if cur == 0:
            break
        if nodes[cur][1] == error:
            print(nodes[cur][2])
            return
        cur = nodes[cur][0]
    print("Unhandled Exception")

#------------------ Python 2 and 3 footer by Pajenegod and c1729-----------------------------------------
py2 = round(0.5)
if py2:
    from future_builtins import ascii, filter, hex, map, oct, zip
    range = xrange

import os, sys
from io import IOBase, BytesIO

BUFSIZE = 8192
class FastIO(BytesIO):
    newlines = 0
    def __init__(self, file):
        self._file = file
        self._fd = file.fileno()
        self.writable = "x" in file.mode or "w" in file.mode
        self.write = super(FastIO, self).write if self.writable else None

    def _fill(self):
        s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
        self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0])
        return s
    def read(self):
        while self._fill(): pass
        return super(FastIO,self).read()

    def readline(self):
        while self.newlines == 0:
            s = self._fill(); self.newlines = s.count(b"\n") + (not s)
        self.newlines -= 1
        return super(FastIO, self).readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.getvalue())
            self.truncate(0), self.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        if py2:
            self.write = self.buffer.write
            self.read = self.buffer.read
            self.readline = self.buffer.readline
        else:
            self.write = lambda s:self.buffer.write(s.encode('ascii'))
            self.read = lambda:self.buffer.read().decode('ascii')
            self.readline = lambda:self.buffer.readline().decode('ascii')

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')

if __name__ == '__main__':
   main()


'''input
3
try
throw ( try )
catch ( try, "try again")
'''
# A coding delight
from sys import stdin

def get_ans(org):
	temp = org.split('"')
	return temp[1]

def get_sign(arr):
	arr = arr.split()
	arr = ''.join(arr)
	arr =  arr.split('(')
	first = arr[1].split(')')
	return first[0]
# main starts
n = int(stdin.readline().strip())
stack = []
stack2 = []
sign = -1
ans = -1
for _ in range(n):
	arr = stdin.readline().strip()
	# print(arr)
	org = arr[:]
	# print(stack, stack2, sign)
	if sign == -1:
		if 'try' in arr and 'catch' not in arr and 'throw' not in arr:
			stack.append(1)
		elif 'catch' in arr and arr.find('catch') < arr.find('throw'):
			stack.pop()

		elif 'throw' in arr:
			sign = get_sign(arr)
	else:
		if  'try' in arr and 'catch' not in arr and 'throw' not in arr:
			stack2.append(1)
		elif 'catch' in arr:
			if len(stack2) == 0:
				if sign in arr:
					ans = get_ans(org)
					break
				else:
					stack.pop()
			else:
				stack2.pop()
if ans != -1:
	print(ans)
else:
	print("Unhandled Exception")


'''input
8
try
    try
        throw ( AE )
    catch ( BE, "BE in line 3")

    try
    catch(AE, "AE in line 5")
catch(AE,"AE somewhere")
'''
# A coding delight
from sys import stdin

def get_ans(org):
	temp = org.split('"')
	return temp[1]

def get_sign(arr):
	arr = arr.split()
	arr = ''.join(arr)
	arr =  arr.split('(')
	first = arr[1].split(')')
	return first[0]
# main starts
n = int(stdin.readline().strip())
stack = []
stack2 = []
sign = -1
ans = -1
for _ in range(n):
	arr = stdin.readline().strip()
	# print(arr)
	org = arr[:]
	# print(stack, stack2)
	if sign == -1:
		if 'try' in arr:
			stack.append(1)
		elif 'catch' in arr:
			stack.pop()

		elif 'throw' in arr:
			sign = get_sign(arr)
	else:
		if  'try' in arr:
			stack2.append(1)
		elif 'catch' in arr:
			if len(stack2) == 0:
				if sign in arr:
					ans = get_ans(org)
					break
				else:
					stack.pop()
			else:
				stack2.pop()
if ans != -1:
	print(ans)
else:
	print("Unhandled Exception")


'''input
3
try
throw ( X )
catch ( X, "try again")
'''
# A coding delight
from sys import stdin

def get_ans(org):
	temp = org.split('"')
	return temp[1]

def get_sign(arr):
	arr = arr.split()
	arr = ''.join(arr)
	arr =  arr.split('(')
	first = arr[1].split(')')
	return first[0]
# main starts
n = int(stdin.readline().strip())
stack = []
stack2 = []
sign = -1
ans = -1
for _ in range(n):
	arr = stdin.readline().strip()
	# print(arr)
	org = arr[:]
	# print(stack, stack2, sign)
	if sign == -1:
		if 'try' in arr:
			stack.append(1)
		elif 'catch' in arr:
			stack.pop()

		elif 'throw' in arr:
			sign = get_sign(arr)
	else:
		if  'try' in arr and 'catch' not in arr:
			stack2.append(1)
		elif 'catch' in arr:
			if len(stack2) == 0:
				if sign in arr:
					ans = get_ans(org)
					break
				else:
					stack.pop()
			else:
				stack2.pop()
if ans != -1:
	print(ans)
else:
	print("Unhandled Exception")


import os,io
from sys import stdout
import collections
# import random
# import math
# from operator import itemgetter
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
# from collections import Counter
# import heapq
# from functools import lru_cache

# import sys
# sys.setrecursionlimit(10**6)

# from functools import lru_cache
# @lru_cache(maxsize=None)

def primes(n):
    sieve = [True] * n
    for i in range(3,int(n**0.5)+1,2):
        if sieve[i]:
            sieve[i*i::2*i]=[False]*((n-i*i-1)//(2*i)+1)
    return [2] + [i for i in range(3,n,2) if sieve[i]]

def binomial_coefficient(n, k):
    if 0 <= k <= n:
        ntok = 1
        ktok = 1
        for t in range(1, min(k, n - k) + 1):
            ntok *= n
            ktok *= t
            n -= 1
        return ntok // ktok
    else:
        return 0

def powerOfK(k, max):
    if k == 1:
        return [1]
    if k == -1:
        return [-1, 1]

    result = []
    n = 1
    while n <= max:
        result.append(n)
        n *= k
    return result

def prefixSum(arr):
    for i in range(1, len(arr)):
        arr[i] = arr[i] + arr[i-1]
    return arr

def divisors(n):
    i = 1
    result = []
    while i*i <= n:
        if n%i == 0:
            if n/i == i:
                result.append(i)
            else:
                result.append(i)
                result.append(n/i)
        i+=1
    return result

def kadane(a,size):
    max_so_far = 0
    max_ending_here = 0

    for i in range(0, size):
        max_ending_here = max_ending_here + a[i]
        if (max_so_far < max_ending_here):
            max_so_far = max_ending_here

        if max_ending_here < 0:
            max_ending_here = 0
    return max_so_far

# @lru_cache(maxsize=None)
def digitsSum(n):
    if n == 0:
        return 0
    r = 0
    while n > 0:
        r += n % 10
        n //= 10
    return r

# INPUTS  --------------------------
# s = input().decode('utf-8').strip()
# n = int(input())
# l = list(map(int, input().split()))
# t = int(input())
# for _ in range(t):

n = int(input())
t = 0
callstack = []
error_codes = {}

import re

lines = []
for _ in range(n):
    line = input().decode('utf-8').strip()
    lines.append(line)

    if line.startswith("try"):
        callstack.append(t)
        t += 1
    elif line.startswith("catch"):
        trynb = callstack.pop()
        exception, message = re.search(r'\((.*)\)',line).group(1).strip().split(',')
        exception, message = exception.strip(), message.strip()[1:-1]
        error_codes[trynb] = (exception, message)

stack_exceptions = []
t = 0
for l in lines:
    if l.startswith("try"):
        stack_exceptions = [error_codes[t]] + stack_exceptions
        t += 1
    elif l.startswith("catch"):
        stack_exceptions = stack_exceptions[1:]
    elif l.startswith("throw"):
        #print(stack_exceptions)
        exc = re.search(r'\((.*)\)',l).group(1).strip()
        for e, m in stack_exceptions:
            if e == exc:
                print(m)
                exit()
        print("Unhandled Exception")
        exit()

t = int(input())
for _ in range(t):
    n, k = list(map(int, input().split()))
    start = 0
    end = 99999999999
    print(solve(n, k, start, end, ""))


import os,io
from sys import stdout
import collections
import random
import math
from operator import itemgetter
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from collections import Counter
import heapq
from functools import lru_cache

import sys
sys.setrecursionlimit(10**6)

# from functools import lru_cache
# @lru_cache(maxsize=None)

def primes(n):
    sieve = [True] * n
    for i in range(3,int(n**0.5)+1,2):
        if sieve[i]:
            sieve[i*i::2*i]=[False]*((n-i*i-1)//(2*i)+1)
    return [2] + [i for i in range(3,n,2) if sieve[i]]

def binomial_coefficient(n, k):
    if 0 <= k <= n:
        ntok = 1
        ktok = 1
        for t in range(1, min(k, n - k) + 1):
            ntok *= n
            ktok *= t
            n -= 1
        return ntok // ktok
    else:
        return 0

def powerOfK(k, max):
    if k == 1:
        return [1]
    if k == -1:
        return [-1, 1]

    result = []
    n = 1
    while n <= max:
        result.append(n)
        n *= k
    return result

def prefixSum(arr):
    for i in range(1, len(arr)):
        arr[i] = arr[i] + arr[i-1]
    return arr

def divisors(n):
    i = 1
    result = []
    while i*i <= n:
        if n%i == 0:
            if n/i == i:
                result.append(i)
            else:
                result.append(i)
                result.append(n/i)
        i+=1
    return result

def kadane(a,size):
    max_so_far = 0
    max_ending_here = 0

    for i in range(0, size):
        max_ending_here = max_ending_here + a[i]
        if (max_so_far < max_ending_here):
            max_so_far = max_ending_here

        if max_ending_here < 0:
            max_ending_here = 0
    return max_so_far

@lru_cache(maxsize=None)
def digitsSum(n):
    if n == 0:
        return 0
    r = 0
    while n > 0:
        r += n % 10
        n //= 10
    return r

# INPUTS  --------------------------
# s = input().decode('utf-8').strip()
# n = int(input())
# l = list(map(int, input().split()))
# t = int(input())
# for _ in range(t):

n = int(input())
t = 0
callstack = []
error_codes = {}
error_message = collections.defaultdict(list)

import re

lines = []
for _ in range(n):
    line = input().decode('utf-8').strip()
    lines.append(line)

    if line.startswith("try"):
        callstack.append(t)
        t += 1
    elif line.startswith("catch"):
        trynb = callstack.pop()
        exception, message = re.search(r'\((.*)\)',line).group(1).strip().split(',')
        exception, message = exception.strip(), message.strip()[1:-1]
        error_message[exception].append(message)
        error_codes[trynb] = (exception, message)

stack_exceptions = []
t = 0
for l in lines:
    if l.startswith("try"):
        stack_exceptions = [error_codes[t]] + stack_exceptions
        t += 1
    elif l.startswith("catch"):
        stack_exceptions = stack_exceptions[1:]
        error_message[exception] = error_message[exception][1:]
    elif l.startswith("throw"):
        #print(stack_exceptions)
        exc = re.search(r'\((.*)\)',l).group(1).strip()
        for e, m in stack_exceptions:
            if e == exc:
                print(m)
                exit()
        print("Unhandled Exception")
        exit()

t = int(input())
for _ in range(t):
    n, k = list(map(int, input().split()))
    start = 0
    end = 99999999999
    print(solve(n, k, start, end, ""))


import os,io
from sys import stdout
import collections
# import random
# import math
# from operator import itemgetter
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
# from collections import Counter
# import heapq
# from functools import lru_cache

# import sys
# sys.setrecursionlimit(10**6)

# from functools import lru_cache
# @lru_cache(maxsize=None)

def primes(n):
    sieve = [True] * n
    for i in range(3,int(n**0.5)+1,2):
        if sieve[i]:
            sieve[i*i::2*i]=[False]*((n-i*i-1)//(2*i)+1)
    return [2] + [i for i in range(3,n,2) if sieve[i]]

def binomial_coefficient(n, k):
    if 0 <= k <= n:
        ntok = 1
        ktok = 1
        for t in range(1, min(k, n - k) + 1):
            ntok *= n
            ktok *= t
            n -= 1
        return ntok // ktok
    else:
        return 0

def powerOfK(k, max):
    if k == 1:
        return [1]
    if k == -1:
        return [-1, 1]

    result = []
    n = 1
    while n <= max:
        result.append(n)
        n *= k
    return result

def prefixSum(arr):
    for i in range(1, len(arr)):
        arr[i] = arr[i] + arr[i-1]
    return arr

def divisors(n):
    i = 1
    result = []
    while i*i <= n:
        if n%i == 0:
            if n/i == i:
                result.append(i)
            else:
                result.append(i)
                result.append(n/i)
        i+=1
    return result

def kadane(a,size):
    max_so_far = 0
    max_ending_here = 0

    for i in range(0, size):
        max_ending_here = max_ending_here + a[i]
        if (max_so_far < max_ending_here):
            max_so_far = max_ending_here

        if max_ending_here < 0:
            max_ending_here = 0
    return max_so_far

# @lru_cache(maxsize=None)
def digitsSum(n):
    if n == 0:
        return 0
    r = 0
    while n > 0:
        r += n % 10
        n //= 10
    return r

# INPUTS  --------------------------
# s = input().decode('utf-8').strip()
# n = int(input())
# l = list(map(int, input().split()))
# t = int(input())
# for _ in range(t):

n = int(input())
t = 0
callstack = []
error_codes = {}

import re

lines = []
for _ in range(n):
    line = input().decode('utf-8').strip()
    lines.append(line)

    if line.startswith("tr"):
        callstack.append(t)
        t += 1
    elif line.startswith("ca"):
        trynb = callstack.pop()
        exception, message = re.search(r'\((.*)\)',line).group(1).strip().split(',')
        exception, message = exception.strip(), message.strip()[1:-1]
        error_codes[trynb] = (exception, message)

stack_exceptions = []
t = 0
for l in lines:
    if l.startswith("tr"):
        stack_exceptions.append(error_codes[t])
        t += 1
    elif l.startswith("ca"):
        stack_exceptions.pop()
    elif l.startswith("th"):
        #print(stack_exceptions)
        exc = re.search(r'\((.*)\)',l).group(1).strip()
        for e, m in stack_exceptions[::-1]:
            if e == exc:
                print(m)
                exit()
        print("Unhandled Exception")
        exit()


import java.io.BufferedReader
import java.io.InputStreamReader

fun main() {
    val jin = BufferedReader(InputStreamReader(System.`in`))
    var exceptionType: String? = null
    var amt = 0
    for (j in 1..jin.readLine().toInt()) {
        var line = jin.readLine().trim()
        if (line.startsWith("try")) {
            if (exceptionType != null) {
                amt++
            }
        } else if (line.startsWith("throw")) {
            line = line.substring(5)
            line = line.trim()
            line = line.substring(1, line.length - 1)
            line = line.trim()
            exceptionType = line
        } else if (line.startsWith("catch")) {
            if (exceptionType != null) {
                if (amt == 0) {
                    line = line.substring(5)
                    line = line.trim()
                    line = line.substring(1, line.length - 1)
                    line = line.trim()
                    val type = line.substringBefore(',').trim()
                    if (type == exceptionType) {
                        line = line.substringAfter(',').trim()
                        line = line.substring(1, line.length - 1)
                        println(line)
                        return
                    }
                } else {
                    amt--
                }
            }
        }
    }
    println("Unhandled Exception")
}


#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<stack>
#include<cctype>
using namespace std;
#define N 110
int main()
{
	int n,ignore_catch=0;
	bool ignore_try=0;
	char str[110],ex_t[110];
	cin.getline(str,N);
	n=atoi(str);
	while(n--)
	{
		cin.getline(str,N);
		int i=0,j;

		// skip spaces nd find t,c
		while (str[i]!='t' && str[i]!='c' && str[i]!='\0') i++;

		// skip empty lines
		if (str[i]=='\0') continue;

		// handle 'throw' lines
		if (str[i]=='t' && str[i+1]=='h')
		{
			while (str[i]!='(') i++;
			i++;
			while(isalpha(str[i])==0)i++;
			j=0;
			while(isalpha(str[i]))
				ex_t[j++] = str[i++];
			ex_t[j]='\0';
			ignore_try = 1;
		}
		else if (str[i]=='t' && str[i+1]=='r')
		{
			if (ignore_try)
			{
				ignore_catch+=1;
			}
		}
		else
		{
			if (ignore_catch>0) ignore_catch--;
			else if (ignore_catch==0 && ignore_try)
			{
				while (str[i]!='(') i++;
				i++;
				while (isalpha(str[i])==0) i++;
				char cstr[110];
				j = 0;
				while (isalpha(str[i])) cstr[j++]=str[i++];
				cstr[j]='\0';
				if (strcmp(ex_t,cstr)==0)
				{
					while (str[i]!=34) i++;
					i++;
					char msg[110];
					j=0;
					while (str[i]!=34) msg[j++]=str[i++];
					msg[j]='\0';
					printf("%s\n",msg);
					return 0;
				}
			}
		}
	}
	printf("Unhandled Exception\n");
	return 0;
}


#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <queue>
#include <vector>
#include <math.h>
#include <stack>
using namespace std;
string s,tmp,key;
stack<int> st;
int main()
{
	int n;cin>>n;
	getline(cin,s);
	int ok=-1;
	while(n--)
	{
		s.clear();
		getline(cin,s);
		//cout<<"len="<<s.size()<<s<<endl;
		if(s.size()==0) continue;
		int i=0;
		while(s[i]==' ') i++;

		if(s[i]=='t')
		{
			if(s[i+1]=='r')
			{
				st.push(0);
			}else
			{
				ok=st.size();
				//cout<<"ok="<<ok<<endl;
				while(s[i]!='(') i++;
				i++;
				while(s[i]==' ') i++;
				while(s[i]!=' '&&s[i]!=')') key+=s[i],i++;
			//	cout<<key<<"??"<<ok<<endl;
			}
		}else
		{
			//cout<<s[i]<<endl;
			while(s[i]!='(') i++;
			i++;
			while(s[i]==' ') i++;
			string now;
			while (s[i]!=','&&s[i]!=' ') now+=s[i],i++;
			while(s[i]!=',')i++;
			//cout<<now<<endl;
			//cout<<now<<"st="<<st.size()<<"  ok= "<<ok<<endl;
			if(now==key&&st.size()<=ok)
			{
			//	cout<<ok<<endl;
				while(s[i]!='\"') i++;
				i++;
				while(s[i]!='\"') cout<<s[i],i++;
				return 0;
			}
			if(st.size()<=ok)
			{
				//cout<<st.size()<<ok<<" ??"<<s<<endl;
				ok--;
				//cout<<ok <<endl;
			}
			st.pop();
		}
	}
	puts("Unhandled Exception");
	return 0;
}


#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <queue>
#include <vector>
#include <math.h>
#include <stack>
using namespace std;
string s,tmp,key;
stack<int> st;
int main()
{
	int n;cin>>n;
	getline(cin,s);
	int ok=-1;
	while(n--)
	{
		s.clear();
		getline(cin,s);
		//cout<<"len="<<s.size()<<s<<endl;
		if(s.size()==0) continue;
		int i=0;
		while(s[i]==' ') i++;

		if(s[i]=='t')
		{
			if(s[i+1]=='r')
			{
				st.push(0);
			}else
			{
				ok=st.size();
				//cout<<"ok="<<ok<<endl;
				while(s[i]!='(') i++;
				i++;
				while(s[i]==' ') i++;
				while(s[i]!=' '&&s[i]!=')') key+=s[i],i++;
	//			cout<<key<<endl;
			}
		}else
		{
			//cout<<s[i]<<endl;
			while(s[i]!='(') i++;
			i++;
			while(s[i]==' ') i++;
			string now;
			while (s[i]!=',') now+=s[i],i++;
			//cout<<now<<endl;
			if(now==key&&st.size()<=ok)
			{
			//	cout<<ok<<endl;
				while(s[i]!='\"') i++;
				i++;
				while(s[i]!='\"') cout<<s[i],i++;
				return 0;
			}
			if(st.size()<=ok)
			{
				//cout<<st.size()<<ok<<" ??"<<s<<endl;
				ok--;
				//cout<<ok <<endl;
			}
			st.pop();
		}
	}
	puts("Unhandled Exception");
	return 0;
}


#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <queue>
#include <vector>
#include <math.h>
#include <stack>
using namespace std;
string s,tmp,key;
stack<int> st;
int main()
{
	int n;cin>>n;
	getline(cin,s);
	int ok=-1;
	while(n--)
	{
		s.clear();
		getline(cin,s);
		//cout<<"len="<<s.size()<<s<<endl;
		if(s.size()==0) continue;
		int i=0;
		//cout<<s.length()<<endl;
		while(s[i]&&s[i]==' ') i++;
		if(s[i]==0) continue;
		if(s[i]=='t')
		{
			if(s[i+1]=='r')
			{
				st.push(0);
			}else
			{
				ok=st.size();
				//cout<<"ok="<<ok<<endl;
				while(s[i]!='(') i++;
				i++;
				while(s[i]==' ') i++;
				while(s[i]!=' '&&s[i]!=')') key+=s[i],i++;
			//	cout<<key<<"??"<<ok<<endl;
			}
		}else
		{
			//cout<<s[i]<<endl;
			while(s[i]!='(') i++;
			i++;
			while(s[i]==' ') i++;
			string now;
			while (s[i]!=','&&s[i]!=' ') now+=s[i],i++;
			while(s[i]!=',')i++;
			//cout<<now<<endl;
			//cout<<now<<"st="<<st.size()<<"  ok= "<<ok<<endl;
			if(now==key&&st.size()<=ok)
			{
			//	cout<<ok<<endl;
				while(s[i]!='\"') i++;
				i++;
				while(s[i]!='\"') cout<<s[i],i++;
				return 0;
			}
			if(st.size()<=ok)
			{
				//cout<<st.size()<<ok<<" ??"<<s<<endl;
				ok--;
				//cout<<ok <<endl;
			}
			st.pop();
		}
	}
	puts("Unhandled Exception");
	return 0;
}


#include <bits/stdc++.h>

using namespace std;
//#define int long long
const int maxN = 100*1000 + 5;
const int mod = 1000*1000*1000 + 7;
string thr(string s)
{
    string res;
    int t = 0;
    for(int i = 0; i < s.size(); i ++)
    {
	  if(s[i] == '(') { t = 1; continue; }
	  if(s[i] == ')') break;
	  if(!t) continue;
	  if(s[i] == ' ') continue;
	  res += s[i];
    }
    return res;
}
string give_op(string s)
{
    string res;
    int t = 0;
    for(int i = 0; i < s.size(); i ++)
    {
	  if(s[i] == '(') { t = 1; continue; }
	  if(s[i] == ',') break;
	  if(!t) continue;
	  if(s[i] == ' ') continue;
	  res += s[i];
    }
    return res;
}
string give_msg(string s)
{
    string res;
    int t = 0;
    for(int i = 0; i < s.size(); i ++)
    {
	  if(s[i] == '"' && t == 1) { break; }
	  if(s[i] == '"') {t = 1; continue; }
	  if(!t) continue;
	  res += s[i];
    }
    return res;
}
main()
{
    ios::sync_with_stdio(0); cin.tie(0);
    int n; cin >> n; cin.ignore();
    vector<string> v;
    string op;
    int cnt = 0;
    vector<int> q;
    for(int i = 0; i < n; i ++)
    {
	  string s; getline(cin, s);

	  int trm = 0, cm = 0, thm = 0;
	  if(s.find("try") == string::npos) trm = mod;
	  else trm = s.find("try");

	  if(s.find("throw") == string::npos) thm = mod;
	  else thm = s.find("throw");

	  if(s.find("catch") == string::npos) cm = mod;
	  else cm = s.find("catch");

	  if(trm < cm && trm < thm) { q.push_back(0); continue; }

	  if(thm < cm && thm < trm)
	  {
		op = thr(s);
		for(int i = 0; i < q.size(); i ++) q[i] = 1;
		continue;
	  }
	  if(cm < thm && cm < trm)
	  {
		if(op == "") continue;
		if(q.back() && give_op(s) == op) { cout << give_msg(s) << endl; return 0; }
		q.pop_back();
	  }
    }
    cout << "Unhandled Exception" << endl;
    return 0;
}


#include <bits/stdc++.h>

using namespace std;
//#define int long long
const int maxN = 100*1000 + 5;
const int mod = 1000*1000*1000 + 7;
string thr(string s)
{
    string res;
    int t = 0;
    for(int i = 0; i < s.size(); i ++)
    {
	  if(s[i] == '(') { t = 1; continue; }
	  if(s[i] == ')') break;
	  if(!t) continue;
	  if(s[i] == ' ') continue;
	  res += s[i];
    }
    return res;
}
string give_op(string s)
{
    string res;
    int t = 0;
    for(int i = 0; i < s.size(); i ++)
    {
	  if(s[i] == '(') { t = 1; continue; }
	  if(s[i] == ',') break;
	  if(!t) continue;
	  if(s[i] == ' ') continue;
	  res += s[i];
    }
    return res;
}
string give_msg(string s)
{
    string res;
    int t = 0;
    for(int i = 0; i < s.size(); i ++)
    {
	  if(s[i] == '"' && t == 1) { break; }
	  if(s[i] == '"') {t = 1; continue; }
	  if(!t) continue;
	  res += s[i];
    }
    return res;
}
main()
{
    ios::sync_with_stdio(0); cin.tie(0);
    int n; cin >> n; cin.ignore();
    vector<string> v;
    string op;
    int cnt = 0;
    vector<int> q;
    for(int i = 0; i < n; i ++)
    {
	  string s; getline(cin, s);

	  if(s.find("try") != string::npos) { q.push_back(0); continue; }
	  if(s.find("throw") != string::npos)
	  {
		op = thr(s);
		for(int i = 0; i < q.size(); i ++) q[i] = 1;
		continue;
	  }
	  if(s.find("catch") != string::npos)
	  {
		if(op == "") continue;
		if(q.back() && give_op(s) == op) { cout << give_msg(s) << endl; return 0; }
		q.pop_back();
	  }
    }
    cout << "Unhandled Exception" << endl;
    return 0;
}