Problem:
Problem B: Red and Black There is a rectangular room, covered with square tiles. Each tile is
colored either red or black. A man is standing on a black tile.
From a tile, he can move to one of four adjacent tiles. But he can't 
move on red tiles, he can move only on black tiles. Write a program to count the number of black tiles which he can reach 
by repeating the moves described above. Input The input consists of multiple data sets.
 A data set starts with a line containing two positive integers W and H ; W and H are the numbers of tiles in the x -
 and y - directions, respectively. W and H are 
not more than 20. There are H more lines in the data set, each of which
includes W characters. Each character represents the color of a
tile as follows.  '.' - a black tile '#' - a red tile '@' - a man on a black tile(appears exactly once in a data set) The end of the input is indicated by a line consisting of two zeros. Output For each data set, your program 
should output a line which contains the number of 
tiles he can reach from the initial tile (including itself). Sample Input 6 9
....#.
.....#
......
......
......
......
......
#@...#
.#..#.
11 9
.#.........
.#.#######.
.#.#.....#.
.#.#.###.#.
.#.#..@#.#.
.#.#####.#.
.#.......#.
.#########.
...........
11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..
7 7
..#.#..
..#.#..
###.###
...@...
###.###
..#.#..
..#.#..
0 0 Output for the Sample Input 45
59
6
13

Solution (Python):
anslist = []
def sarch(i, j, visited):

    if 0 < i:
        if visited[i - 1][j] == 0:
            visited[i - 1][j] = 1
            sarch(i - 1, j, visited)
    if i < len(visited) - 1:
        if visited[i + 1][j] == 0:
            visited[i + 1][j] = 1
            sarch(i + 1, j, visited)
    if 0 < j:
        if visited[i][j - 1] == 0:
            visited[i][j - 1] = 1
            sarch(i, j - 1, visited)
    if j < len(visited[0]) - 1:
        if visited[i][j + 1] == 0:
            visited[i][j + 1] = 1
            sarch(i, j + 1, visited)
    return visited


while True:
    w, h = map(int, input().split())
    if w == 0 and h == 0:
        break
    grid = [list(input()) for i in range(h)]
    visited = [[0 for i in range(w)] for j in range(h)]
    starti = 0
    startj = 0
    for i in range(h):
        for j in range(w):
            if grid[i][j] == "@":
                starti = i
                startj = j
                visited[i][j] = 1
            elif grid[i][j] == "
                visited[i][j] = -1
            else:
                visited[i][j] = 0

    visited = sarch(starti, startj, visited)
    
    ans = 0
    for i in visited:
        for j in i:
            if j == 1:
                ans += 1
    anslist.append(ans)

for i in anslist:
    print(i)

Solution (Python):
from queue import Queue

def calcReachableTileNumByBFSearch(room, start_pos):
    q = Queue()
    q.put(start_pos)

    count = 1
    while not q.empty():
        cur_pos = q.get()
        D0 = [1, 0, -1, 0]
        D1 = [0, -1, 0, 1]
        for d in range(4):
            nc = [0,0]
            nc[0] = cur_pos[0]+D0[d]
            nc[1] = cur_pos[1]+D1[d]
            if room[nc[0]][nc[1]] == '.':
                room[nc[0]][nc[1]] = '*'
                q.put([nc[0],nc[1]])
                count +=1
    return count


def solve(width, height):
    room = [['
    for i in range(height):
        row = input()
        for j in range(width):
            room[i+1][j+1] = row[j]
            if room[i+1][j+1] == '@':
                start = [i+1,j+1]

    return calcReachableTileNumByBFSearch(room, start)


def main():
    while True:
        width, height = map(int, input().split())
        if width == 0 and height == 0:
            break
        print(solve(width, height))


if __name__ == "__main__":
    main()

Solution (Python):
while 1:
    x, y = list(map(int,input().split()))
    if x == 0:break

    mx = [1,-1,0,0]
    my = [0,0,1,-1]
    m = []
    for i in range(y):
        m.append(list(input()))
        if '@' in m[-1]:
            sx = m[-1].index('@')
            sy = i
    cnt = 0

    def move(cur_x, cur_y):
        global cnt
        if cur_y >= y or cur_y < 0 or cur_x >= x or cur_x < 0:return
        if m[cur_y][cur_x] == '.' or m[cur_y][cur_x] == '@':
            cnt += 1
            m[cur_y][cur_x] = '0'
            for i in range(4):
                move(cur_x + mx[i],cur_y + my[i])
    move(sx,sy)
    print(cnt)

Solution (Python):



def dfs(s,Map,H,W):
    dxdy = [(1,0),(-1,0),(0,1),(0,-1)]
    for i in range(4):
        Map[s[0]][s[1]] = '*'
        nextPos = (s[0]+dxdy[i][0],s[1]+dxdy[i][1])
        if nextPos[0] >= 0 and nextPos[1] >= 0 and nextPos[0] < H and nextPos[1] < W:
            if Map[nextPos[0]][nextPos[1]] == '.':
                dfs(nextPos,Map,H,W)

while True:
    W,H = map(int,input().split(" "))
    if W == 0 and H == 0:
        break
    Map = [list(input()) for i in range(0,H)]
    for i in range(H):
        for j in range(W):
            if Map[i][j] == '@':
                S = (i,j)

    dfs(S,Map,H,W)
    print(sum([1 if Map[i][j] == '*' else 0 for i in range(H) for j in range(W)]))

Solution (Python):
def search(here, lb, ub, field):
	count = 0
	if field[here[1]][here[0]] :
		count += 1
		field[here[1]][here[0]] = 0
		if lb[0] < here[0] :
			count += search((here[0]-1, here[1]), lb, ub, field) 
		if lb[1] < here[1] :
			count += search((here[0], here[1]-1), lb, ub, field)
		if ub[0] > here[0] :
			count += search((here[0]+1, here[1]), lb, ub, field)
		if ub[1] > here[1] :
			count += search((here[0], here[1]+1), lb, ub, field) 
	return count

while 1:
	w, h = map(int, raw_input().split(" "))
	if (w,h) == (0,0): 
		break
	field = [[1 for i in range(w)] for j in range(h)]
	for y in range(h):
		tiles = raw_input()
		for x in range(w):
			if tiles[x] == "
				field[y][x] = 0
			elif tiles[x] == "@":
				here = (x,y)
	print search(here, (0,0), (w-1,h-1), field)

Solution (Python):



def rec(x, y, used, TILE):
    if not(0<=x<W) or not(0<=y<H):
        return
    elif used[y][x]==1 or TILE[y][x]=='
        return
    else:
        used[y][x] = 1
        rec(x-1, y, used, TILE)
        rec(x+1, y, used, TILE)
        rec(x, y-1, used, TILE)
        rec(x, y+1, used, TILE)

(W, H) = map(int, raw_input().split())
while W!=0:
    used = [[0]*W for i in range(H)]
    TILE = []
    s = []
    for i in range(H):
        TILE.append(raw_input())
    for i in range(H):
        for j in range(W):
            if TILE[i][j] == '@':
                s = [i, j]

    
    
    
    rec(s[1], s[0], used, TILE)
    Sum = 0
    for i in range(H):
        Sum += used[i].count(1)
    print Sum
    

    (W, H) = map(int, raw_input().split())

Solution (Python):
def search(x, y, m):
    if x < 0 or y < 0 \
            or x >= len(m[0]) or y >= len(m):
        return 0
    if m[y][x] == '
        return 0
    m[y][x] = '
    return 1 + search(x+1,y, m) + search(x-1,y,m) \
            + search(x,y+1,m) + search(x,y-1,m)

while True:
    w, h = map(int, input().split())
    if w == 0: break
    room = []
    for i in range(h):
        tmp = list(input())
        room.append(tmp[:w])
        if '@' in tmp:
            y = i
            x = tmp.index('@') 
    print(search(x, y, room))

Solution (Python):
delta = ((1, 0), (0, 1), (-1, 0), (0, -1))
def ds(here, lb, ub, field):
	if field[here[1]][here[0]] == "
		return 0
	result = 1
	field[here[1]][here[0]] = "
	for dx, dy in delta:
		next = (here[0]+dx,here[1]+dy)
		if lb[0] <= next[0] < ub[0] and lb[1] <= next[1] < ub[1]:
			result += ds(next, lb, ub, field)
	return result
while 1:
	W, H = map(int,raw_input().split(" "))
	if W == H == 0:
		break
	floor = [list(raw_input()) for i in range(H)]
	start = None
	for i in range(H):
		for j in range(W):
			if floor[i][j] == "@":
				start = (j,i)
				break
		if start is not None:
			break
	print ds(start,(0,0),(W,H),floor)

Solution (Python):
def dfs(x, y):
    for dx in [-1, 0, 1]:
        for dy in [-1, 0, 1]:
            if abs(dx) + abs(dy) == 2 or abs(dx) + abs(dy) == 2:
                continue
            next_x, next_y = x + dx, y + dy
            if 0 <= next_x < H and 0 <= next_y < W and isVisited[next_x][next_y] == 0 and tile[next_x][next_y] == '.':
                isVisited[next_x][next_y] = 1
                dfs(next_x, next_y)
                
                

while True:
    W, H = map(int, raw_input().split())
    if W == 0 and H == 0: break
    tile = [raw_input() for _ in range(H)]
    ans = 0
    isVisited = [[0]*W for _ in range(H)]
    for cnt, t in enumerate(tile):
        if '@' in t:
            sx = cnt
            sy = t.index('@')
            break
    isVisited[sx][sy] = 1
    dfs(sx, sy)
    print sum([sum(v) for v in isVisited])

Solution (Python):
delta = ((1, 0), (0, 1), (-1, 0), (0, -1))
def ds(here, lb, ub, field):
	if field[here[1]][here[0]] == "
		return 0
	result = 1
	field[here[1]][here[0]] = "
	for dx, dy in delta:
		next = (here[0]+dx,here[1]+dy)
		if lb[0] <= next[0] < ub[0] and lb[1] <= next[1] < ub[1]:
			result += ds(next, lb, ub, field)
	return result
while 1:
	W, H = map(int,raw_input().split(" "))
	if W == H == 0:
		break
	floor = [list(raw_input()) for i in range(H)]
	start = None
	for i in range(H):
		for j in range(W):
			if floor[i][j] == "@":
				start = (j,i)
				break
		if start is not None:
			break
	print ds(start,(0,0),(W,H),floor)

Solution (Python):
def dfs(tiles, w, h, x, y):
    cnt = 1
    tiles[y][x] = '@'
    for dx,dy in ((0,1), (0,-1), (-1,0), (1,0)):
        if 0<=x+dx<w and 0<=y+dy<h and tiles[y+dy][x+dx]=='.':
            cnt += dfs(tiles, w, h, x+dx, y+dy)
    return cnt

def main():
    while True:
        W,H = [int(x) for x in input().split()]
        if W==0 and H==0:
            exit()
        tiles = [[c for c in input()] for h in range(H)]
        for i in range(H):
            if '@' in tiles[i]:
                Y = i
                X = tiles[i].index('@')
        answer = dfs(tiles, W, H, X, Y)
        print(answer)

if __name__ == '__main__':
    main()

Solution (Python):

def get_start(tile, h, w):
	for i in range(w):
		for j in range(h):
			if tile[i][j] == '@':
				return (i, j)

dirs = [(-1, 0), (0, -1), (1, 0), (0, 1)]

while True:
	w, h = map(int, input().split())
	if (w,h) == (0,0):
		break
	tile = [list(input()) for i in range(h)]
	start = get_start(tile, w, h)
	count = 0
	q = [start]
	while q:
		(x,y) = q.pop()
		for d in dirs:
			xx = x+d[0]
			yy = y+d[1]
			if (0 <= xx and xx < h) and (0 <= yy and yy < w):
				if tile[xx][yy] == '.':
					tile[xx][yy] = '_'
					count += 1
					q.append((xx,yy))
	print(count+1)

Solution (Python):
def check(x, y, count):
	array[x][y] = "$"
	count += 1
	if array[x + 1][y] == "." : count = check(x + 1, y, count)
	if array[x - 1][y] == "." : count = check(x - 1, y, count)
	if array[x][y + 1] == "." : count = check(x, y + 1, count)
	if array[x][y - 1] == "." : count = check(x, y - 1, count)
	return count

while True:
	h,w = map(int, raw_input().split())
	if h == 0 and w == 0 : break

	array = []
	array.append(list("$" * (h + 2)))
	for i in range(0, w) : array.append(list("$" + raw_input() + "$"))
	array.append(list("$" * (h + 2)))
	
	x = 1
	y = 1
	for i in range(1, w + 1):
		if "@" in array[i]:
			x = i
			y = array[i].index("@")
	
	print check(x, y, 0)

Solution (Python):
vx = [1, -1, 0, 0]
vy = [0, 0, 1, -1]


def isBound(n, m, x, y):
    return x < 0 or y < 0 or x >= n or y >= m


def dfs(x, y):
    global field
    global cnt
    global v

    if isBound(W, H, x, y):
        return
    if field[y][x] == '
        return
    if v[y][x]:
        return
    else:
        v[y][x] = True
        cnt += 1

    for i in range(4):
        nx = x + vx[i]
        ny = y + vy[i]
        dfs(nx, ny)

while True:
    W, H = map(int, raw_input().split())

    if W == 0:
        break

    field = []
    for h in range(H):
        field.append(raw_input())

    v = [[False for i in range(W)] for j in range(H)]

    cnt = 0
    for x in range(W):
        for y in range(H):
            if field[y][x] == '@':
                dfs(x, y)
    print cnt

Solution (Python):



import array
import itertools
import sys


UNDET_POINT = (-1, -1)


class RecursiveDepthFirstSearch(object):

    def __init__(self, width, height, tiles):
        self.width = width
        self.height = height
        self.tiles = tiles
        self.reached = [array.array(
            "B", (False for j in range(height))) for i in range(width)]
        self.start_tile = UNDET_POINT
        for x, y in itertools.product(range(width), range(height)):
            if tiles[x][y] == "@":
                self.start_tile = (x, y)
                break

    def search(self, x, y):
        if x < 0 or self.width <= x or y < 0 or self.height <= y:
            pass
        elif self.tiles[x][y] == "
            pass
        elif self.reached[x][y]:
            pass
        else:
            self.reached[x][y] = True
            self.search(x + 1, y)
            self.search(x - 1, y)
            self.search(x, y + 1)
            self.search(x, y - 1)

    def count_reachable_tiles(self):
        self.search(*self.start_tile)
        reachable_tiles = sum([self.reached[x][y] for x, y in itertools.product(
            range(self.width), range(self.height))])
        return reachable_tiles


if __name__ == "__main__":
    sys.setrecursionlimit(10000)
    while True:
        width, height = map(int, input().split())
        if width == 0 and height == 0:
            break
        else:
            tiles = [x for x in zip(*[input() for y in range(height)])]
            dfs = RecursiveDepthFirstSearch(width, height, tiles)
            print(dfs.count_reachable_tiles())

Solution (Python):



import array
import collections
import itertools


class DepthFirstSearchWithStack(object):

    def __init__(self, width, height, tiles):
        self.width = width
        self.height = height
        self.tiles = tiles
        self.reached = [array.array(
            "B", (False for y in range(height))) for x in range(width)]
        for x, y in itertools.product(range(width), range(height)):
            if tiles[x][y] == "@":
                self.start_tile = (x, y)
                break

    def search(self, x0, y0):
        stack = collections.deque()
        self.reached[x0][y0] = True
        stack.append((x0, y0))
        while stack:
            (x, y) = stack.pop()
            for i, j in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]:
                if i < 0 or self.width <= i or j < 0 or self.height <= j:
                    pass
                elif self.tiles[i][j] == "
                    pass
                elif not self.reached[i][j]:
                    self.reached[i][j] = True
                    stack.append((i, j))

    def count_reachable_tiles(self):
        self.search(*self.start_tile)
        reachable_tiles = sum([self.reached[x][y] for x, y in itertools.product(
            range(self.width), range(self.height))])
        return reachable_tiles


if __name__ == "__main__":
    while True:
        width, height = map(int, input().split())
        if width == 0 and height == 0:
            break
        else:
            tiles = [x for x in zip(*[input() for y in range(height)])]
            dfs = DepthFirstSearchWithStack(width, height, tiles)
            print(dfs.count_reachable_tiles())

Solution (Python):
import sys

ct=1
def count(Map, w,h,i, j):
    global ct
    dx=[1,0,-1,0]
    dy=[0,1,0,-1]
    for k in range(4):
        ix=i+dy[k]
        jx=j+dx[k]
        if (0<=ix<h and 0<=jx<w and Map[ix][jx]=='.'):
            Map[ix][jx]='
            ct+=1
            count(Map,w,h,ix,jx)

while(True):
    input = map(int, sys.stdin.readline().replace('\n','').split(' '))
    w,h=input
    if(w==0 and h==0):break
    Map=[]
    for i in range(h):
        s=raw_input()
        Map.append(list(s))
        
    flag=False
    for i in range(h):
        for j in range(w):
            if (Map[i][j]=='@'):
                flag=True
                Map[i][j]='
                break
        if flag:break

    ct=1
    count(Map,w,h,i,j)
    print ct

Solution (Python):
from Queue import Queue

while True:
    q = Queue()
    w, h = map(int, raw_input().split())
    tile = [[0 for i in range(w)] for j in range(h)]
    if w == 0: break
    for i in range(h):
        tile[i] = raw_input()
        for j in range(w):
            if tile[i][j] == '@':
                q.put([i,j])
    
    count = 0
    while q.empty() == False:
        node = q.get()
        y = node[0]
        x = node[1]
        count += 1
        for i,j in zip([1,-1,0,0],[0,0,1,-1]):
            if (0 <= y+i < h and 0 <= x+j < w) == False: continue
            if tile[y+i][x+j] == '.':
                tilist = list(tile[y+i])
                tilist[x+j] = '@'
                tile[y+i] = "".join(tilist)
                q.put([y+i,x+j])
    print count

Solution (Python):
count = 0
role = {".": True, "@": False, "
def now(xpoint, ypoint):
    return role[room[ypoint][xpoint]]

def search(xpoint, ypoint):
    global count
    if 0 <= xpoint < wh[0] and 0 <= ypoint < wh[1] and now(xpoint, ypoint):
        count += 1
        room[ypoint][xpoint] = "@"
        search(xpoint - 1, ypoint)
        search(xpoint + 1, ypoint)
        search(xpoint, ypoint + 1)
        search(xpoint, ypoint - 1)

while True:
    wh = map(int, raw_input().split())
    room = []
    count = 0
    for ypoint in range(wh[1]):
        line = raw_input().replace("\n", "")
        if "@" in line:
            xp = line.index("@")
            yp = ypoint
        room.append([x for x in line])
    if not room: break
    room[yp][xp] = "."
    search(xp, yp)
    print count

Solution (Python):
(lambda f: f(f))(lambda this, atin=lambda line, yp, ri=lambda l: room.append([{xi: x} for xi, x in enumerate(l)]): [point.__setitem__("x", line.index("@")), point.__setitem__("y", yp), ri(line)] if "@" in line else ri(line), search=lambda xpoint, ypoint, srch, now: [room[ypoint][xpoint].__setitem__(xpoint, "@"), srch(xpoint - 1, ypoint, srch, now) + srch(xpoint + 1, ypoint, srch, now) + srch(xpoint, ypoint + 1, srch, now) + srch(xpoint, ypoint - 1, srch, now) + 1][1] if 0 <= xpoint < wh[0] and 0 <= ypoint < wh[1] and now(xpoint, ypoint) else 0, now=lambda xpoint, ypoint: room[ypoint][xpoint].get(xpoint) is ".": [globals().__setitem__("wh", list(map(int, input().split()))), globals().__setitem__("room", []), globals().__setitem__("point", {"x": None, "y": None}), [atin(input(), ypoint) for ypoint in range(wh[1])], [room[point["y"]][point["x"]].__setitem__(point["x"], "."), print(search(point["x"], point["y"], search, now)), this(this)] if room else None])

Solution (Python):
(lambda f:f(f))(lambda T,A=lambda L,yp,ri=lambda l:R.append([{xi:x}for xi,x in enumerate(l)]):[P.__setitem__("x",L.index("@")),P.__setitem__("y",yp),ri(L)]if "@"in L else ri(L),S=lambda X,Y,s,u:[R[Y][X].__setitem__(X,"@"),s(X-1,Y,s,u)+s(X+1,Y,s,u)+s(X,Y+1,s,u)+s(X,Y-1,s,u)+1][1]if 0<=X<W[0]and 0<=Y<W[1]and u(X,Y)else 0,u=lambda X,Y:R[Y][X].get(X)is ".",g=globals:[g().__setitem__("W",list(map(int,input().split()))),g().__setitem__("R",[]),g().__setitem__("P",{"x":9,"y":9}),[A(input(),Y)for Y in range(W[1])],[R[P["y"]][P["x"]].__setitem__(P["x"],"."),print(S(P["x"],P["y"],S,u)),T(T)]if R else 9])

Solution (Python):

while True:
    W, H = [int(n) for n in input().split()]

    if W == H == 0:
        break

    next_target = []

    room = []
    for n in range(H):
        s = list(input())
        room.append(s)
        for y in range(W):
            if s[y] == '@':
                next_target.append((n, y))

    result = 0

    while len(next_target) > 0:
        t = next_target.pop()

        
        if t[0] - 1 >= 0 and room[t[0] - 1][t[1]] == '.':
            next_target.append((t[0] - 1, t[1]))
            room[t[0] - 1][t[1]] = '@'

        
        if t[1] + 1 < W and room[t[0]][t[1] + 1] == '.':
            next_target.append((t[0], t[1] + 1))
            room[t[0]][t[1] + 1] = '@'

        
        if t[0] + 1 < H and room[t[0] + 1][t[1]] == '.':
            next_target.append((t[0] + 1, t[1]))
            room[t[0] + 1][t[1]] = '@'

        
        if t[1] - 1 >= 0 and room[t[0]][t[1] - 1] == '.':
            next_target.append((t[0], t[1] - 1))
            room[t[0]][t[1] - 1] = '@'

        
        result += 1

    print(result)

Solution (Python):
def getter(targ,x,y):
    
    if 0 > x or x >= len(targ) or 0 > y or y >= len(targ[0]) or targ[x][y] == '
        return 0
    else:
        targ[x][y] = '
        return 1 + getter(targ,x+1,y) + getter(targ,x-1,y) + getter(targ,x,y+1) + getter(targ,x,y-1)
width,height = [int(n) for n in input().split(" ")]
global lab
while True:
    lab,start = [],[]
    for a in range(height):
        disp = [n for n in input().rstrip('\n')]
        if '@' in disp:
            start.extend([disp.index('@'),a])
        lab.append(disp)
    else:
        a,b = start
        print(getter(lab,b,a))
        width,height = [int(n) for n in input().split(" ")]
        if width == 0 and height == 0:
            break

Solution (Python):


def Is_black(coo):
    a = coo[0]
    b = coo[1]
    if 0 <= a < l[1] and 0 <= b < l[0] and \
    map_list[a][b] == '.':
        return True
    else:
        return False

while True:
    l = map(int, raw_input().split())
    if l == [0, 0]:
        break
    else:
        map_list = []
        for i in range(l[1]):
            row = str(raw_input())
            if '@' in row:
                fp = (i, row.find('@'))
            map_list.append(row)
        stack = [fp]
        arrived = [fp]
        while stack:
            coo = stack.pop()
            coo_a = (coo[0], coo[1] + 1)
            coo_b = (coo[0], coo[1] - 1)
            coo_c = (coo[0] + 1, coo[1])
            coo_d = (coo[0] - 1, coo[1])
            coo_l = [coo_a, coo_b, coo_c, coo_d]
            for c in coo_l:
                if Is_black(c) and c not in arrived:
                    stack.append(c)
                    arrived.append(c)
        print len(arrived)

Solution (Python):
d = [[-1,0],[1,0],[0,-1],[0,1]]
def search(w,h,x,y,m):
    if not(0<=x<w and 0<=y<h) or m[y][x]=='
    m[y][x] = '
    return sum([search(w,h,x+dx,y+dy,m) for dx,dy in d])+1

while True:
    w,h = map(int,input().split())
    if w==h==0: break
    m = []
    for i,l in enumerate([list(input()) for _ in range(h)]):
        if '@' in l: x,y = l.index('@'),i
        m += [l]
    print(search(w,h,x,y,m))

Solution (Python):
mx = [0, 1, 0, -1]
my = [-1, 0, 1, 0]

while True:
    w, h = map(int, input().split())
    if w == h == 0:
        break
    tiles = [[i for i in input()] for j in range(h)]
    ax = ay = 0
    for i in range(h):
        for j in range(w):
            if tiles[i][j] == '@':
                ax, ay = j, i
    que = [(ax, ay)]
    tiles[ay][ax] = '
    cnt = 1

    while 0 < len(que):
        new_que = []
        for x, y in que:
            for i in range(4):
                nx, ny = x + mx[i], y + my[i]
                if 0 <= nx <= w - 1 and 0 <= ny <= h - 1:
                    if tiles[ny][nx] == '.':
                        cnt += 1
                        new_que.append((nx, ny))
                        tiles[ny][nx] = '
        que = new_que
    print(cnt)

Solution (Python):
I=input
def f(x,y,r):
    if not(0<=x<len(r[0])and(0<=y<len(r)))or r[y][x]=='
    r[y][x]='
    return 1+sum(f(x+dx,y+dy,r)for dx,dy in[[-1,0],[1,0],[0,-1],[0,1]])
while 1:
    w,h=map(int,I().split())
    if w==0:break
    r=[list(input()) for _ in[0]*h]
    for a,b in enumerate(r):
        if '@'in b:y=a;x=b.index('@');break
    print(f(x,y,r))

Solution (Python):
def move_a(y,x,count):
    count += 1
    li[x][y] = "
    if li[x-1][y] == ".":
        count = move_a(y,x-1,count)
    if li[x+1][y]== ".":
        count = move_a(y,x+1, count)
    if li[x][y-1]== ".":
        count = move_a(y-1,x, count)
    if li[x][y+1]== ".":
        count = move_a(y+1,x, count)
    return count

while True:
    yoko, tate = map(int,raw_input().split())
    if yoko == 0 and tate == 0:
        break
    li = []
    rec_list = []
    count = 0
    li.append(["

    for i in range(tate):
        temp = raw_input()
        temp = "
        li.append(list(temp))
    li.append(["
    for i in li:
        if '@' in i:
            a_posx,a_posy = i.index('@'),li.index(i)
    print move_a(a_posx,a_posy,count)

Solution (Python):
import Queue

while True:
    w, h = [int(_) for _ in raw_input().split()]
    if w == h == 0:
        break
    dat = [list(raw_input()) for _ in xrange(h)]
    queue = Queue.Queue()
    for y, r in enumerate(dat):
        if "@" in r:
            queue.put([r.index("@"), y])

    while not queue.empty():
        x, y = queue.get()
        for dx, dy in [[1, 0], [0, 1], [-1, 0], [0, -1]]:
            if not (0 <= x + dx < w) or not (0 <= y + dy < h):
                continue
            if dat[y + dy][x + dx] == ".":
                dat[y + dy][x + dx] = "@"
                queue.put([x + dx, y + dy])

    ans = 0
    for r in dat:
        ans += r.count("@")

    print(ans)

Solution (Python):


import sys

def dfs(rw,cm):
    global flag
    flag[rw][cm] = 1
    if 0 <= rw - 1 and mp[rw-1][cm] == '.' and flag[rw-1][cm] == 0:
        dfs(rw-1,cm)
    if cm + 1 < m and mp[rw][cm+1] == '.' and flag[rw][cm+1] == 0:
        dfs(rw,cm+1)
    if 0 <= cm - 1 and mp[rw][cm-1] == '.' and flag[rw][cm-1] == 0:
        dfs(rw,cm-1)
    if rw + 1 < n and mp[rw+1][cm] == '.' and flag[rw+1][cm] == 0:
        dfs(rw+1,cm)

if __name__ == '__main__':
    while 1:
        m,n = map(int,input().split())
        if m == 0 and n == 0:
            break
        mp = []
        for i in range(n):
            mp.append(list(input()))
            if '@' in mp[-1]:
                stj = mp[-1].index('@')
                sti = i
        flag = [[0 for i in range(m)] for j in range(n)]
        dfs(sti,stj)
        print(sum(flag[i].count(1) for i in range(n)))

Solution (Python):
import sys
from collections import deque

def solve():
    while 1:
        w, h = map(int, sys.stdin.readline().split())

        if w == h == 0:
            return

        room = [[False]*w for i in range(h)]

        si = sj = -1

        for i in range(h):
            line = input()

            for j, ch in enumerate(line):
                if ch == '@':
                    room[i][j] = True
                    si = i
                    sj = j
                elif ch == '.':
                    room[i][j] = True

        ans = bfs(w, h, room, si, sj)

        print(ans)

dx = (1, 0, -1, 0,)
dy = (0, 1, 0, -1,)

def bfs(w, h, room, si, sj):
    visited = [[False]*w for i in range(h)]
    visited[si][sj] = True
    q = deque([(si, sj)])
    cnt = 1

    while q:
        ci, cj = q.popleft()

        for k in range(len(dx)):
            ni = ci + dy[k]
            nj = cj + dx[k]

            if 0 <= ni < h and 0 <= nj < w and room[ni][nj] and not visited[ni][nj]:
                visited[ni][nj] = True
                q.append((ni, nj))
                cnt += 1

    return cnt

if __name__ == '__main__':
    solve()

Solution (Python):
import sys

cnt = 0

def solve():
    while 1:
        w, h = map(int, sys.stdin.readline().split())

        if w == h == 0:
            return

        room = [list(sys.stdin.readline().rstrip()) for i in range(h)]

        for i in range(h):
            if '@' in room[i]:
                si = i
                sj = room[i].index('@')
                break

        global cnt
        cnt = 0
        dfs(w, h, room, si, sj)
        print(cnt)

def dfs(w, h, room, i, j):
    if i < 0 or i >= h or j < 0 or j >= w or (room[i][j] == '
        return

    global cnt
    cnt += 1
    room[i][j] = '

    dfs(w, h, room, i + 1, j)
    dfs(w, h, room, i - 1, j)
    dfs(w, h, room, i, j + 1)
    dfs(w, h, room, i, j - 1)

if __name__ == '__main__':
    solve()

Solution (Python):
while True:
    w, h = map(int, input().split())
    if w == 0:
        break
    a = []
    for i in range(h):
        t = list(input())
        a.append(t)
        if '@' in t:
            x = i
            y = t.index('@')
    stk = [[x, y]]
    c = 1
    while True:
        if stk == []:
            break
        x, y = stk.pop()
        if y != w-1 and a[x][y+1] == '.':
            a[x][y+1] = '@'
            stk.append([x, y+1])
        if y != 0 and a[x][y-1] == '.':
            a[x][y-1] = '@'
            stk.append([x, y-1])
        if x != h-1 and a[x+1][y] == '.':
            a[x+1][y] = '@'
            stk.append([x+1, y])
        if x != 0 and a[x-1][y] == '.':
            a[x-1][y] = '@'
            stk.append([x-1, y])
    print(sum([t.count('@') for t in a]))

Solution (Python):
c = {"
     "@":1,
     ".":2,
     "*":3}

d = [[0, -1],
     [0, 1],
     [-1, 0],
     [1, 0]]

output = []
while True:
    w, h = input().split()
    w = int(w)
    h = int(h)

    if w == 0:
        break

    tiles = [[0 for i in range(w)] for j in range(h)]
    for i in range(h):
        row = input()
        for j in range(w):
            tiles[i][j] = c[row[j]]
            if tiles[i][j] == 1:
                queue = [(j, i)]

    count = 1
    while queue:
        x, y = queue[0]
        queue.pop(0)

        for ud, rl in d:
            xt = x+ud
            yt = y+rl
            if xt >= 0 and xt <= w-1 and yt >= 0 and yt <= h-1:
                if tiles[yt][xt] == 2:
                    tiles[yt][xt] = 3
                    count += 1
                    queue.append((xt, yt))

    output.append(count)

for num in output:
    print(num)

Solution (Python):
def dfs(graph, sx, sy):
    stack = [[sx, sy]]
    visited = []
    cnt = 0
    while stack:
        label = stack.pop(0)
        try:
            g = graph[label[1]][label[0]]
            if (label[0] < 0) or (label[0] > graph[0].__len__() - 1):
                continue
            if (label[1] < 0) or (label[1] >graph.__len__() - 1):
                continue
            if g == '
                continue
            if [label[0], label[1]] not in visited:
                
                cnt += 1
                visited = [[label[0], label[1]]] + visited
                stack = [[label[0]+1, label[1]], [label[0]-1, label[1]], [label[0], label[1]+1], [label[0], label[1]-1]] + stack
        except IndexError:
            pass
    return cnt


if __name__ == '__main__':
    STR = []
    W, H = [int(i) for i in input().split()]
    while W != 0:
        for j in range(H):
            STR.append(list(input()))
            if '@' in STR[j]:
                sx, sy = STR[j].index('@'), j
        print(dfs(STR, sx, sy))
        STR = []
        W, H = [int(i) for i in input().split()]

Solution (Python):
def floodfill(matrix, x, y):
    global count
    
    if (matrix[x][y] == ".") or (matrix[x][y] == "@"):
        count += 1
        matrix[x][y] = "check"
        
        if x > 0:
            floodfill(matrix, x - 1, y)
        if x < len(matrix) - 1:
            floodfill(matrix, x + 1, y)
        if y > 0:
            floodfill(matrix, x, y - 1)
        if y < len(matrix[0]) - 1:
            floodfill(matrix, x, y + 1)
    return count

while True:
    x, y = map(int, input().split())
    if x == y == 0: break
    room = []
    for i in range(y):
        room.append([i for i in input()])

    for key, list in enumerate(room):
        if "@" in list:
            ax, ay = key, list.index("@")

    count = 0
    print(floodfill(room, ax, ay))