Igor is in the museum and he wants to see as many pictures as possible.

Museum can be represented as a rectangular field of n × m cells. Each cell is either empty or impassable. Empty cells are marked with '.', impassable cells are marked with '*'. Every two adjacent cells of different types (one empty and one impassable) are divided by a wall containing one picture.

At the beginning Igor is in some empty cell. At every moment he can move to any empty cell that share a side with the current one.

For several starting positions you should calculate the maximum number of pictures that Igor can see. Igor is able to see the picture only if he is in the cell adjacent to the wall with this picture. Igor have a lot of time, so he will examine every picture he can see.


-----Input-----

First line of the input contains three integers n, m and k (3 ≤ n, m ≤ 1000, 1 ≤ k ≤ min(n·m, 100 000)) — the museum dimensions and the number of starting positions to process.

Each of the next n lines contains m symbols '.', '*' — the description of the museum. It is guaranteed that all border cells are impassable, so Igor can't go out from the museum.

Each of the last k lines contains two integers x and y (1 ≤ x ≤ n, 1 ≤ y ≤ m) — the row and the column of one of Igor's starting positions respectively. Rows are numbered from top to bottom, columns — from left to right. It is guaranteed that all starting positions are empty cells.


-----Output-----

Print k integers — the maximum number of pictures, that Igor can see if he starts in corresponding position.


-----Examples-----
Input
5 6 3
******
*..*.*
******
*....*
******
2 2
2 5
4 3

Output
6
4
10

Input
4 4 1
****
*..*
*.**
****
3 2

Output
8

Difficulty: interview

Starter code:

Solutions:
#!/usr/bin/env python3
# 598D_Igor.py - Codeforces.com/problemset/problem/598/D by Sergey 2015

import unittest
import sys
from collections import deque

###############################################################################
# Igor Class (Main Program)
###############################################################################


def empty_around(i, rc, n, m, nw, mw):
    w = 32
    r = (i // m) // w
    c = (i % m) // w
    j = r * mw + c
    if j < len(rc):
        if rc[j] == 0:
            rc[j] = 1
            return True, r, c
    return False, 0, 0


def fill_around(a, r0, c0, to_visit, visited, n, m):
    w = 32
    for r in range(w):
        for c in range(w):
            i = (r0 * w + r) * m + (c0 * w + c)
            if (r == 0 or r == w - 1 or c == 0 or c == w - 1):
                if a[i] == 0:
                    to_visit.append(i)
                    a[i] = 1
            else:
                a[i] = 2
                visited.append(i)


class Igor:
    """ Igor representation """

    def __init__(self, test_inputs=None):
        """ Default constructor """

        it = iter(test_inputs.split("\n")) if test_inputs else None

        def uinput():
            return next(it) if it else sys.stdin.readline().rstrip()

        self.result = []
        w = 32
        n, m, k = [int(x) for x in uinput().split()]
        d0, d1, d2, d3 = -m, 2*m, -m-1, 2
        a = []
        rc = []
        rr = []
        mw = m // w
        nw = n // w
        for _ in range(n):
            row = [(0 if v == '.' else 3) for v in uinput()]
            a += row
            rc += [sum(row[i*w:i*w+w]) for i in range(mw)]
        for i in range(nw):
            j = i*mw*w
            rr += [sum([rc[j+u*mw+v] for u in range(w)]) for v in range(mw)]
        to_visit = deque()
        for _ in range(k):
            x0, y0 = [int(x)-1 for x in uinput().split()]
            i0 = x0*m+y0
            step = 0
            if a[i0] > 3:
                self.result.append(a[i0])
            else:
                ans = 0
                to_visit.append(i0)
                visited = deque()
                step += 1
                while to_visit:
                    i = to_visit.pop()
                    if a[i] == 2:
                        continue
                    visited.append(i)
                    if step % w == 1:
                        e, r0, c0 = empty_around(i, rr, n, m, nw, mw)
                    else:
                        e = False
                    a[i] = 2
                    if e:
                        fill_around(a, r0, c0, to_visit, visited, n, m)
                    for d in (d0, d1, d2, d3):
                        i += d
                        if a[i] == 0:
                            to_visit.append(i)
                            a[i] = 1
                        elif a[i] == 3:
                            ans += 1
                self.result.append(ans)
                for i in visited:
                    a[i] = ans

    def calculate(self):
        """ Main calcualtion function of the class """

        return str("\n".join(map(str, self.result)))

###############################################################################
# Unit Tests
###############################################################################


class unitTests(unittest.TestCase):

    def test_single_test(self):
        """ Igor class testing """

        # Constructor test
        test = "5 6 3\n******\n*..*.*\n******\n*....*\n******\n2 2\n2 5\n4 3"
        d = Igor(test)

        # Sample test
        self.assertEqual(Igor(test).calculate(), "6\n4\n10")

        # Sample test
        test = ""
        # self.assertEqual(Igor(test).calculate(), "0")

        # Sample test
        test = ""
        # self.assertEqual(Igor(test).calculate(), "0")

        # My tests
        test = ""
        # self.assertEqual(Igor(test).calculate(), "0")

        # Time limit test
        # self.time_limit_test(5000)

    def time_limit_test(self, nmax):
        """ Timelimit testing """
        import random
        import timeit

        # Random inputs
        test = str(nmax) + " " + str(nmax) + "\n"
        numnums = [str(i) + " " + str(i+1) for i in range(nmax)]
        test += "\n".join(numnums) + "\n"
        nums = [random.randint(1, 10000) for i in range(nmax)]
        test += " ".join(map(str, nums)) + "\n"

        # Run the test
        start = timeit.default_timer()
        d = Igor(test)
        calc = timeit.default_timer()
        d.calculate()
        stop = timeit.default_timer()
        print(("\nTimelimit Test: " +
              "{0:.3f}s (init {1:.3f}s calc {2:.3f}s)".
              format(stop-start, calc-start, stop-calc)))

def __starting_point():

    # Avoiding recursion limitaions
    sys.setrecursionlimit(100000)

    if sys.argv[-1] == "-ut":
        unittest.main(argv=[" "])

    # Print the result string
    sys.stdout.write(Igor().calculate())

__starting_point()

import sys
from queue import deque

# sys.stdin = open('ivo.in')

move = [(0, 1), (1, 0), (0, -1), (-1, 0)]
n, m, k = map(int, sys.stdin.readline().split())

a = []
for i in range(n):
    a.append(sys.stdin.readline().rstrip())


visited = []
values = []
for x in range(n):
    visited.append([])
    values.append([])
    for y in range(m):
        visited[x].append(False)
        values[x].append(0)


for x in range(n):
    for y in range(m):
        if a[x][y] == '*' or visited[x][y]:
            continue
        q = deque()
        visited[x][y] = True
        q.append((x, y))
        sum = 0
        connected = [(x, y)]
        while len(q) != 0:
            cur = q.pop()
            for l in move:
                tx = cur[0] + l[0]
                ty = cur[1] + l[1]
                if tx < 0 or tx >= n or ty < 0 or ty >= m:
                    continue
                if a[tx][ty] == '.' and visited[tx][ty]:
                    continue
                if a[tx][ty] == '*':
                    sum += 1
                    continue
                q.append((tx, ty))
                visited[tx][ty] = True
                connected.append((tx, ty))
        for c in connected:
            values[c[0]][c[1]] = sum

for i in range(k):
    x, y = map(int, sys.stdin.readline().split())
    print(values[x - 1][y - 1])

import sys
 
def get_array(): return list(map(int, sys.stdin.readline().split()))
def get_ints(): return map(int, sys.stdin.readline().split())
def input(): return sys.stdin.readline().strip('\n')
 
 
visited = []
out = []
 
for i in range(1010):
    visited.append([])
    out.append([])
    for j in range(1010):
        visited[i].append(0)
        out[i].append(-1)


def dfs(x,y):
    cells = []
    c = 0
    Q = [(x,y)]
    while Q:
        x,y = Q.pop()
        if x >= n or x < 0 or y >= m or y < 0:
            return
        if l[x][y] == '*':
            c += 1
            continue
        if visited[x][y] :
           continue
        visited[x][y] = 1
        cells.append((x,y))
        Q.append((x+1,y))
        Q.append((x-1,y))
        Q.append((x,y+1))
        Q.append((x,y-1))
    
    for x in cells:
        if visited[x[0]][x[1]] and out[x[0]][x[1]] == -1:
            out[x[0]][x[1]] = c
 
n , m , k = get_ints()
l = []
for i in range(n):
    l.append(input())
 
for i in range(n):
    for j in range(m):
        if not visited[i][j] and l[i][j] == '.':
            dfs(i,j)
            
for i in range(k):
    x , y = get_ints()
    x , y = x-1 , y-1
    ans = out[x][y]
    print(ans)

import sys

def get_array(): return list(map(int, sys.stdin.readline().split()))
def get_ints(): return map(int, sys.stdin.readline().split())
def input(): return sys.stdin.readline().strip('\n')

visited = []
out = []

for i in range(1010):
    visited.append([])
    out.append([])
    for j in range(1010):
        visited[i].append(0)
        out[i].append(-1)
cells = []
def dfs(x,y):
    nonlocal c
    Q = [(x,y)]
    while Q:
        x,y = Q.pop()
        if x >= n or x < 0 or y >= m or y < 0:
            continue
        if l[x][y] == '*':
            c += 1
            continue
        if visited[x][y] :
            continue
        visited[x][y] = 1
        cells.append((x,y))
        Q.append((x+1,y))
        Q.append((x,y+1))
        Q.append((x-1,y))
        Q.append((x,y-1))

n , m , k = get_ints()
l = []
for i in range(n):
    l.append(list(input()))

for i in range(n):
    for j in range(m):
        if not visited[i][j] and l[i][j] == '.':
            c = 0
            dfs(i,j)
            for x in cells:
                if visited[x[0]][x[1]] and out[x[0]][x[1]] == -1:
                    out[x[0]][x[1]] = c
            cells.clear()
for i in range(k):
    x , y = get_ints()
    x , y = x-1 , y-1
    ans = out[x][y]
    print(ans)

import sys

def get_array(): return list(map(int, sys.stdin.readline().split()))
def get_ints(): return list(map(int, sys.stdin.readline().split()))
def input(): return sys.stdin.readline().strip('\n')

cells = []

''' Using pajenegod dfs '''
def dfs(x,y):
    nonlocal c
    q = [(x,y)]

    while q:
        x, y = q.pop()
        if x >= n or x < 0 or y >= m or y < 0:
            continue
        if l[x][y] == '*':
            c += 1
            continue
        if visited[x][y]:
            continue
        
        visited[x][y] = 1
        cells.append((x,y))
        q.append((x+1,y))
        q.append((x,y+1))
        q.append((x-1,y))
        q.append((x,y-1))

n , m , k = get_ints()
l = []
for i in range(n):
    l.append(list(input()))

visited = []
out = []

for i in range(n+10):
    visited.append([0]*(m+10))
    out.append([-1]*(m+10))
    
for i in range(n):
    for j in range(m):
        if not visited[i][j] and l[i][j] == '.':
            c = 0
            dfs(i,j)
            for x in cells:
                if visited[x[0]][x[1]] and out[x[0]][x[1]] == -1:
                    out[x[0]][x[1]] = c
            cells.clear()
for i in range(k):
    x , y = get_ints()
    x , y = x-1 , y-1
    print(out[x][y])


import sys

def get_array(): return list(map(int, sys.stdin.readline().split()))
def get_ints(): return list(map(int, sys.stdin.readline().split()))
def input(): return sys.stdin.readline().strip('\n')

cells = []

''' Using Pajenegod's dfs '''
def dfs(x,y):
    nonlocal c
    q = [(x,y)]

    while q:
        x, y = q.pop()
        if x >= n or x < 0 or y >= m or y < 0:
            continue
        if l[x][y] == '*':
            c += 1
            continue
        if visited[x][y]:
            continue
        
        visited[x][y] = 1
        cells.append((x,y))
        q.append((x+1,y))
        q.append((x,y+1))
        q.append((x-1,y))
        q.append((x,y-1))

n , m , k = get_ints()
l = []
for i in range(n):
    l.append(list(input()))

visited = []
out = []

for i in range(n+10):
    visited.append([0]*(m+10))
    out.append([-1]*(m+10))
    
for i in range(n):
    for j in range(m):
        if not visited[i][j] and l[i][j] == '.':
            c = 0
            dfs(i,j)
            for x in cells:
                if visited[x[0]][x[1]] and out[x[0]][x[1]] == -1:
                    out[x[0]][x[1]] = c
            cells.clear()
for i in range(k):
    x , y = get_ints()
    x , y = x-1 , y-1
    print(out[x][y])