Igor In the Museum (Codeforces 598D)
Tags: Others, shortest paths

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.


Sample Inputs:
5 6 3
******
*..*.*
******
*....*
******
2 2
2 5
4 3

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

Sample Outputs:
6
4
10

8

Solution (Python):
import os, sys
from io import BytesIO, IOBase
from collections import deque

def main():
    (n, m, Q) = map(int, input().split())
    arr = [input().strip() for _ in range(n)]
    dp = [[0] * m for _ in range(n)]
    (ans, comp, dx, dy) = ([], 0, [-1, 1, 0, 0], [0, 0, -1, 1])
    for i in range(n):
        for j in range(m):
            if dp[i][j] or arr[i][j] == '*':
                continue
            comp += 1
            val = 0
            dp[i][j] = comp
            curr = deque([(i, j)])
            while len(curr):
                (x, y) = curr.popleft()
                for k in range(4):
                    (x1, y1) = (x + dx[k], y + dy[k])
                    if arr[x1][y1] != '*' and (not dp[x1][y1]):
                        curr.append((x1, y1))
                        dp[x1][y1] = comp
                    elif arr[x1][y1] == '*':
                        val += 1
            ans.append(val)
    for _ in range(Q):
        (a, b) = map(lambda xx: int(xx) - 1, input().split())
        if not dp[a][b]:
            print(0)
        else:
            print(ans[dp[a][b] - 1])
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')
if __name__ == '__main__':
    main()

Solution (Python):
import sys, io, os
from atexit import register
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
sys.stdout = io.BytesIO()
register(lambda : os.write(1, sys.stdout.getvalue()))

def print(args=[], sep=' ', end='\n', file=sys.stdout):
    first = True
    sep = sep.encode()
    for a in args:
        if first:
            first = False
        else:
            file.write(sep)
        file.write(str(a).encode())
    file.write(end.encode())
visited = [[0] * 1010 for _ in range(1010)]
out = [[-1] * 1010 for _ in range(1010)]
cells = []

def dfs(x, y):
    global 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] == b'*'[0]:
            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) = [int(x) for x in input().split()]
l = [input() for _ in range(n)]
for i in range(n):
    for j in range(m):
        if not visited[i][j] and l[i][j] == b'.'[0]:
            c = 0
            dfs(i, j)
            while cells:
                x = cells.pop()
                if visited[x[0]][x[1]] and out[x[0]][x[1]] == -1:
                    out[x[0]][x[1]] = c
ANS = []
for i in range(k):
    (x, y) = [int(x) for x in input().split()]
    ANS.append(out[x - 1][y - 1])
print(ANS, sep='\n')

Solution (Python):
import sys, io, os
from atexit import register
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
sys.stdout = io.BytesIO()
register(lambda : os.write(1, sys.stdout.getvalue()))
visited = [[0] * 1002 for _ in range(1002)]
out = [[-1] * 1002 for _ in range(1002)]
(n, m, k) = [int(x) for x in input().split()]
l = [input() for _ in range(n)]
Q = []
for j in range(m):
    for i in range(n):
        if not visited[i][j] and l[i][j] == b'.'[0]:
            c = 0
            Q.append((i, j))
            ind = 0
            while ind < len(Q):
                (x, y) = Q[ind]
                ind += 1
                if x >= n or x < 0 or y >= m or (y < 0):
                    continue
                if l[x][y] == b'*'[0]:
                    c += 1
                    continue
                if visited[x][y]:
                    continue
                visited[x][y] = 1
                Q.append((x + 1, y))
                Q.append((x, y + 1))
                Q.append((x - 1, y))
                Q.append((x, y - 1))
            while Q:
                (x, y) = Q.pop()
                out[x][y] = c
for i in range(k):
    (x, y) = [int(x) for x in input().split()]
    sys.stdout.write(str(out[x - 1][y - 1]).encode())
    sys.stdout.write(b'\n')