def area(room, location, history, portals, size = 0):
    size += 1
    print room[location[0]][location[1]]
    history.append(location)
    if portals.has_key(room[location[0]][location[1]]) and not(portals[room[location[0]][location[1]]] in history):
        size += area(room, portals[room[location[0]][location[1]]], history, portals)
    if (location[0]+1 < len(room)):
        if not((location[0]+1,location[1]) in history) and room[location[0]+1][location[1]] != "#":          
                size += area(room, (location[0]+1,location[1]), history, portals)
    if (location[0]-1 >= 0):
        if not((location[0]-1,location[1]) in history) and room[location[0]-1][location[1]] != "#":
                size += area(room, (location[0]-1,location[1]), history, portals)
    if (location[1]+1 < len(room[location[0]])):
        if not((location[0],location[1]+1) in history) and room[location[0]][location[1]+1] != "#":
                size += area(room, (location[0],location[1]+1), history, portals)
    if (location[1]-1 >= 0):
        if not((location[0],location[1]-1) in history) and room[location[0]][location[1]-1] != "#":
                size += area(room, (location[0],location[1]-1), history, portals)
    return size

portals = {"a": None,"A": None,"b": None,"B": None,"c": None,"C": None,"d": None,"D": None,"e": None,"E": None,"f": None,"F": None,"g": None,"G": None,"h": None,"H": None,"i": None,"I": None,"j":None,"J":None}
rnumbers = {"1": None,"2": None,"3": None,"4": None,"5": None}

filein = open("DATA5.txt","U")
out = open("OUT5.txt","w")

asd = [list(x.rstrip()) for x in filein.readlines()[2:]]

print asd

for y,line in enumerate(asd):
    for x,ch in enumerate(line):
        loc = (int(y),int(x))
        if portals.has_key(ch):
            if ch == ch.upper(): portals[ch.lower()] = loc
            else: portals[ch.upper()] = loc
        elif rnumbers.has_key(ch): rnumbers[ch] = loc

for n in ["1","2","3","4","5"]:
    out.write("%i\n" % area(asd, rnumbers[n], [], portals))
out.close()

