#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<queue>
#define N 105
using namespace std;
int key[N][N];
char a[N][N];
int vis[N][N][1<<5];
int dir[4][2] = {
1, 0, -1, 0, 0, 1, 0, -1
};
struct node {
int x, y, val, s;
};
int n, m, K;
bool OK( int e, int r )
{
return (e >= 1 && e <= n && r >= 1 && r <= m);
}
int bfs( node st )
{
memset(vis, 0, sizeof(vis));
queue<node> q;
while( !q.empty() )
q.pop();
st.s = 0;
st.val = key[st.x][st.y];
vis[st.x][st.y][ key[st.x][st.y] ] = 1;
q.push(st);
while( !q.empty() )
{
node now = q.front();
q.pop();
if ( now.val == (1 << (K+1)) - 2)
return now.s;
for ( int i = 0; i < 4; i++ )
{
int xx = dir[i][0] + now.x;
int yy = dir[i][1] + now.y;
if( OK(xx, yy) && a[xx][yy] != '#' && !vis[xx][yy][now.val] )
{
node tmp;
tmp.x = xx;
tmp.y = yy;
tmp.s = now.s + 1;
tmp.val = now.val | key[xx][yy];
vis[xx][yy][tmp.val] = 1;
q.push(tmp);
}
}
}
return -1;
}
int main()
{
while(~scanf("%d%d", &n, &m) && (m || n))
{
for( int i = 1; i <= n; i++ )
scanf("%s", a[i] + 1);
memset( key, 0, sizeof(key) );
int sx, sy;
for ( int i = 1; i <= n; i++ )
{
for( int j = 1; j <= m; j++ )
{
if ( a[i][j] == '@' )
{
sx = i;
sy = j;
break;
}
}
}
node st;
st.x = sx, st.y = sy;
scanf("%d", &K);
int e, r;
for( int i = 1; i <= K; i++ )
{
scanf("%d%d", &e, &r);
key[e][r] |= (1 << i);
}
int ans = bfs(st);
printf("%d\n", ans);
}
return 0;
}
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<queue>
#define N 105
using namespace std;
int key[N][N];
char a[N][N];
int vis[N][N][1<<5];
int dir[4][2] = {
1, 0, -1, 0, 0, 1, 0, -1
};
struct node {
int x, y, val, s;
};
int n, m, K;
bool OK( int e, int r )
{
return (e >= 1 && e <= n && r >= 1 && r <= m);
}
int bfs( node st )
{
memset(vis, 0, sizeof(vis));
queue<node> q;
while( !q.empty() )
q.pop();
st.s = 0;
st.val = key[st.x][st.y];
vis[st.x][st.y][ key[st.x][st.y] ] = 1;
q.push(st);
while( !q.empty() )
{
node now = q.front();
q.pop();
if ( now.val == (1 << (K+1)) - 2)
return now.s;
for ( int i = 0; i < 4; i++ )
{
int xx = dir[i][0] + now.x;
int yy = dir[i][1] + now.y;
if( OK(xx, yy) && a[xx][yy] != '#' && !vis[xx][yy][now.val] )
{
node tmp;
tmp.x = xx;
tmp.y = yy;
tmp.s = now.s + 1;
tmp.val = now.val | key[xx][yy];
vis[xx][yy][tmp.val] = 1;
q.push(tmp);
}
}
}
return -1;
}
int main()
{
while(~scanf("%d%d", &n, &m) && (m || n))
{
for( int i = 1; i <= n; i++ )
scanf("%s", a[i] + 1);
memset( key, 0, sizeof(key) );
int sx, sy;
for ( int i = 1; i <= n; i++ )
{
for( int j = 1; j <= m; j++ )
{
if ( a[i][j] == '@' )
{
sx = i;
sy = j;
break;
}
}
}
node st;
st.x = sx, st.y = sy;
scanf("%d", &K);
int e, r;
for( int i = 1; i <= K; i++ )
{
scanf("%d%d", &e, &r);
key[e][r] |= (1 << i);
}
int ans = bfs(st);
printf("%d\n", ans);
}
return 0;
}