import sys


def main():
    algorithm, _, *image_lines = map(str.strip, sys.stdin)

    image = {
        (x, y): c for y, line in enumerate(image_lines) for x, c in enumerate(line)
    }

    infinite_pixel = "."

    for enhancement in range(50):
        min_x = min(x for x, y in image)
        min_y = min(y for x, y in image)

        max_x = max(x for x, y in image)
        max_y = max(y for x, y in image)

        new_image = {}

        for y in range(min_y - 1, max_y + 2):
            for x in range(min_x - 1, max_x + 2):
                number = 0

                for dy in [-1, 0, 1]:
                    for dx in [-1, 0, 1]:
                        number *= 2
                        number += image.get((x + dx, y + dy), infinite_pixel) == "#"

                new_image[x, y] = algorithm[number]

        image = new_image
        infinite_pixel = [algorithm[0], algorithm[-1]][infinite_pixel == "#"]

        if enhancement in [1, 49]:
            print(sum(c == "#" for c in image.values()))


if __name__ == "__main__":
    main()
