#include <bits/stdc++.h>
using namespace std;
int sx, sy;
const int N = 3000;
int n, m, k, cnt = 0, fir[N], nxt[N << 1], to[N << 1], vis[N], cxy[N], nx = 0, p[N][N], cans = 0, ans[N], win[N], del[N];
char a[N][N];
void ade(int u, int v) {
cnt++, nxt[cnt] = fir[u], fir[u] = cnt, to[cnt] = v;
cnt++, nxt[cnt] = fir[v], fir[v] = cnt, to[cnt] = u;
}
int dfs(int r) {
vis[r] = 1;
for (int i = fir[r]; i; i = nxt[i])
if (!vis[to[i]] && !del[to[i]]) {
vis[to[i]] = 1;
if (!cxy[to[i]] || dfs(cxy[to[i]])) {
cxy[cxy[r]] = 0, cxy[to[i]] = r, cxy[r] = to[i];
return 1;
}
}
return 0;
}
void match() {
for (int i = 1; i <= nx; i++)
if (!cxy[i])
memset(vis, 0, sizeof(vis)), dfs(i);
}
void getp() {//分成X,Y两部重标号
int tmp = 0;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
if (a[i][j] == 'O')
p[i][j] = ++tmp;
nx = tmp;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
if (a[i][j] == 'X') p[i][j] = ++tmp;
else if (a[i][j] == '.') p[i][j] = ++tmp, sx = i, sy = j;
}
int dx[5] = {0, 1, 0, -1};
int dy[5] = {1, 0, -1, 0};
void edge(int x, int y) {
for (int i = 0; i < 4; i++) {
int xx = x + dx[i], yy = y + dy[i];
if (xx >= 1 && xx <= n && yy >= 1 && yy <= m && p[xx][yy] > nx) ade(p[x][y], p[xx][yy]);
}
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) scanf("%s", a[i] + 1);
getp();
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
if (a[i][j] == 'O')
edge(i, j);
match();
scanf("%d", &k);
for (int t = 1; t <= k * 2; t++) {
del[p[sx][sy]] = 1;
if (!cxy[p[sx][sy]]) continue;
int tmp = cxy[p[sx][sy]];
cxy[p[sx][sy]] = cxy[tmp] = 0, memset(vis, 0, sizeof(vis));
if (!dfs(tmp)) win[t] = 1;
scanf("%d%d", &sx, &sy);
}
for (int i = 2; i <= k * 2; i += 2)
if (win[i] == 1 && win[i - 1] == 1)
ans[++cans] = i / 2;
printf("%d\n", cans);
for (int i = 1; i <= cans; i++) printf("%d\n", ans[i]);
return 0;
}