#!/usr/bin/env python3

# This does now work. Falsely assumes that all letters "on the side" can be replaced by their minimum

import itertools

lines = [list(input()) for _ in range(6)]

# Replace all side-faces with their minimum letter, to get the time down to 3^16

alphabet = [0, 1, 2] # top, side, bottom

solutions = set()
for string in itertools.product(alphabet, repeat=16):
    prev = '@' # precedes 'A'
    cost = 0
    for i, l in enumerate(string):
        if l == 0:
            char = lines[0][i]
        elif l == 2:
            char = lines[5][i]
        elif l == 1:
            char = min((lines[l][i] for l in range(1, 5) if lines[l][i] >= prev), default='@')
        cost += l
        if char < prev:
            break
        prev = char
        if prev == 'Q':
            prev = 'U'
    else:
        solutions.add(cost)
print('impossible' if not solutions else min(solutions))
