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



Sample input:
6 9
....#.
.....#
......
......
......
......
......
#@...#
.#..#.
11 9
.#.........
.#.#######.
.#.#.....#.
.#.#.###.#.
.#.#..@#.#.
.#.#####.#.
.#.......#.
.#########.
...........
11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..
7 7
..#.#..
..#.#..
###.###
...@...
###.###
..#.#..
..#.#..
0 0


Sample output:
45
59
6
13

Submission status: Accepted

Solution code:
(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])

Submission status: Accepted

Solution code:
(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])

Submission status: Accepted

Solution code:

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)

Submission status: Accepted

Solution code:
def getter(targ,x,y):
    #print(x,y,len(targ[0]),len(targ))
    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

Submission status: Accepted

Solution code:
#coding: utf-8

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)

Submission status: Accepted

Solution code:
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]=='#': return 0
    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))

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
I=input
def f(x,y,r):
    if not(0<=x<len(r[0])and(0<=y<len(r)))or r[y][x]=='#':return 0
    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))

Submission status: Accepted

Solution code:
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(["#"] * (yoko + 2))

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

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
# coding: utf-8

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)))

Submission status: Accepted

Solution code:
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()

Submission status: Accepted

Solution code:
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()

Submission status: Accepted

Solution code:
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]))

Submission status: Accepted

Solution code:
c = {"#":0,
     "@":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)

Submission status: Accepted

Solution code:
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:
                # graph[label[1], label[0]] = '#'
                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()]

Submission status: Accepted

Solution code:
def floodfill(matrix, x, y):
    global count
    #"hidden" stop clause - not reinvoking for "check" or "#", only for "," or "@".
    if (matrix[x][y] == ".") or (matrix[x][y] == "@"):
        count += 1
        matrix[x][y] = "check"
        #recursively invoke flood fill on all surrounding cells:
        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))

Submission status: Accepted

Solution code:
W,H=(int(i) for i in input().split())
while W!=0 or H!=0:
    a=[]
    T=[]
    for i in range(H):
        T.append(input())
        a.append([])
        for j in range(W):
            a[i].append(0)
 #   print(T[0][0])
    i=0
    j=0
    while T[i][j]!="@":
        j=0
        while j<W and T[i][j]!="@":
            j+=1
    #        print(j)
        if j>=W:
            j-=1
        if T[i][j]!="@":
            i+=1
  #      print(i)
    s=[[i,j]]
    a[i][j]=1
    c=1
    while s!=[]:
        u=[]
        for l in range(len(s)):
            i=s[l][0]
            j=s[l][1]
            i-=1
            k=0
            while k<2:
            #    print(j)
                if 0<=i<H and a[i][j]==0 and T[i][j]==".":
                    a[i][j]=1
                    u.append([i,j])
                    c+=1
                i+=2
                k+=1
            i-=3
            j-=1
            k=0
            while k<2:
                if 0<=j<W and a[i][j]==0 and T[i][j]==".":
                    a[i][j]=1 
                    u.append([i,j])
                    c+=1
                j+=2
                k+=1
        s=u
    #    print (a)
    print(c)
    W,H=(int(i) for i in input().split())

Submission status: Accepted

Solution code:
#data????§???????[y???][x???]??§??????

if __name__ == "__main__":
    while 1:
        w,h = list(map(int,input().strip().split()))
        if w == h == 0:break
        data = []
        data = []
        for _ in range(h):data.append(list(input()))
        visited = []
        position =(0,0)
        for i in range(h):
            if '@'in data[i]:position = (i,data[i].index('@'))
        stack = []
        count = 0
        stack.append(position)
        while len(stack) !=0:
            position = stack.pop()
            count +=1
            if position[0] -1 >= 0 and not (position[0]-1,position[1])in visited and data[position[0] -1][position[1]] == '.':
                visited.append((position[0] -1,position[1]))
                stack.append((position[0] -1,position[1]))
            if position[1] -1 >= 0 and not (position[0],position[1]-1)in visited and data[position[0]][position[1]-1] == '.':
                visited.append((position[0],position[1]-1))
                stack.append((position[0],position[1]-1))
            if position[0] +1 < h and not (position[0]+1,position[1])in visited and data[position[0] +1][position[1]] == '.':
                visited.append((position[0]+1,position[1]))
                stack.append((position[0]+1,position[1]))
            if position[1] + 1 < w and not (position[0],position[1]+1)in visited and data[position[0]][position[1] +1] == '.':
                visited.append((position[0],position[1] +1))
                stack.append((position[0],position[1]+1))

        print(count)

Submission status: Accepted

Solution code:
#data????§???????[y???][x???]??§??????

if __name__ == "__main__":
    while 1:
        w,h = list(map(int,input().strip().split()))
        if w == h == 0:break
        data = []
        data = []
        for _ in range(h):data.append(list(input()))
        visited = []
        position =(0,0)
        for i in range(h):
            if '@'in data[i]:position = (i,data[i].index('@'))
        stack = []
        count = 0
        stack.append(position)
        while len(stack) !=0:
            y,x= stack.pop()
            count +=1
            if y-1 >= 0 and not (y-1,x)in visited and data[y -1][x] == '.':
                visited.append((y-1,x))
                stack.append((y-1,x))
            if x -1 >= 0 and not (y,x-1)in visited and data[y][x-1] == '.':
                visited.append((y,x-1))
                stack.append((y,x-1))
            if y +1 < h and not (y+1,x)in visited and data[y +1][x] == '.':
                visited.append((y+1,x))
                stack.append((y+1,x))
            if x + 1 < w and not (y,x+1)in visited and data[y][x +1] == '.':
                visited.append((y,x+1))
                stack.append((y,x+1))

        print(count)

Submission status: Accepted

Solution code:
#data????§???????[y???][x???]??§??????

if __name__ == "__main__":
    while 1:
        w,h = list(map(int,input().strip().split()))
        if w == h == 0:break
        data = []
        data = []
        for _ in range(h):data.append(list(input()))
        visited = []
        for i in range(h):
            if '@'in data[i]:stack= [(i,data[i].index('@'))]
        count = 0
        while len(stack) !=0:
            y,x= stack.pop()
            count +=1
            if y-1 >= 0 and not (y-1,x)in visited and data[y -1][x] == '.':
                visited.append((y-1,x))
                stack.append((y-1,x))
            if x -1 >= 0 and not (y,x-1)in visited and data[y][x-1] == '.':
                visited.append((y,x-1))
                stack.append((y,x-1))
            if y +1 < h and not (y+1,x)in visited and data[y +1][x] == '.':
                visited.append((y+1,x))
                stack.append((y+1,x))
            if x + 1 < w and not (y,x+1)in visited and data[y][x +1] == '.':
                visited.append((y,x+1))
                stack.append((y,x+1))

        print(count)

Submission status: Accepted

Solution code:
import queue

def solve(w, h):
    q = queue.Queue()
    m = [['#' for i in range(w+2)] for j in range(h+2)]
    for i in range(h):
        inp = input()
        for j in range(w):
            m[i+1][j+1] = inp[j]
            if m[i+1][j+1] == '@':
                start = [i+1,j+1]
    q.put(start)
    c = 1
    while not q.empty():
        cur = q.get()
        XY = [(1,0), (-1, 0), (0, 1), (0, -1)]
        for x, y in XY:
            cx = cur[0]+x
            cy = cur[1]+y
            if m[cx][cy] == '.':
                m[cx][cy] = '#'
                q.put([cx, cy])
                c+=1
    return c

while True:
    w, h = [int(i) for i in input().split()]
    if w == 0 and h == 0:
        break
    print(solve(w,h))

Submission status: Accepted

Solution code:
while 1:
	w,h = map(int, raw_input().split())
	if w == h == 0:
		break
	count = 0
	cnt = 1
	lst = [list(raw_input()) for i in range(h)]
	queue = []
	for i in range(h):
		if "@" in lst[i]:
			wNow, hNow = lst[i].index("@"),i
	queue.append([hNow, wNow])
	while 1:
		hNow,wNow = queue[0][0],queue[0][1]
		queue.pop(0)
		if hNow < h-1:
			if lst[hNow+1][wNow] == ".":
				queue.append([hNow+1,wNow])
				lst[hNow+1][wNow] = "$"
				cnt += 1
		if wNow < w-1:
			if lst[hNow][wNow+1] == ".":
				queue.append([hNow,wNow+1])
				lst[hNow][wNow+1] = "$"
				cnt += 1
		if hNow > 0:
			if lst[hNow-1][wNow] == ".":
				queue.append([hNow-1,wNow])
				lst[hNow-1][wNow] = "$"
				cnt += 1
		if wNow > 0:
			if lst[hNow][wNow-1] == ".":
				queue.append([hNow,wNow-1])
				lst[hNow][wNow-1] = "$"
				cnt += 1
		if len(queue) == 0:
			break
	print cnt

Submission status: Accepted

Solution code:
from collections import deque
while True:
    W,H = map(int,input().split())
    if W == 0: break
    src = [input() for i in range(H)]
    for y,row in enumerate(src):
        x = row.find('@')
        if x < 0: continue
        sx,sy = x,y
        break
    visited = [[0 for x in range(W)] for y in range(H)]
    visited[sy][sx] = 1
    q = deque([(sx,sy)])
    ans = 1
    while q:
        x,y = q.popleft()
        for dx,dy in zip([1,0,-1,0],[0,1,0,-1]):
            nx,ny = x+dx,y+dy
            if not(0 <= nx < W) or not(0 <= ny < H): continue
            if src[ny][nx] == '#' or visited[ny][nx]: continue
            visited[ny][nx] = 1
            ans += 1
            q.append((nx,ny))
    print(ans)

Submission status: Accepted

Solution code:
import copy
w, h = map(int,input().split())
while [h, w] != [0, 0]:
    area = []
    a = 1
    for i in range(h):
        area.append(list(input()))
        area[i].insert(0,"#")
        area[i].append("#")
    area.insert(0,["#" for i in range(w + 2)])
    area.append(["#" for i in range(w + 2)])

    que = []
    for i in range(1, h + 1):
        for j in range(1, w + 1):
            if area[i][j] == "@":
                que.append([i, j])
                break
        else:
            continue
        break
    while True:
        nque = []
        for i in que:
            h1 = i[0]
            w1 = i[1]
            if area[h1 - 1][w1] == ".":
                area[h1 - 1][w1] = "*"
                nque.append([h1 - 1, w1])
                a += 1
            if area[h1 + 1][w1] == ".":
                area[h1 + 1][w1] = "*"
                nque.append([h1 + 1, w1])
                a += 1
            if area[h1][w1 - 1] == ".":
                area[h1][w1 - 1] = "*"
                nque.append([h1, w1 - 1])
                a += 1
            if area[h1][w1 + 1] == ".":
                area[h1][w1 + 1] = "*"
                nque.append([h1, w1 + 1])
                a += 1
        if nque == []:
            break
        que = copy.deepcopy(nque)

    print(a)
        
    w, h = map(int,input().split())

Submission status: Accepted

Solution code:
from queue import Queue

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

    tile = [input() for i in range(h)]
    for x, col in enumerate(tile):
        if '@' in col:
            y = col.index('@')
            s = (x, y)
            break

    visit = [[False for i in range(w)] for j in range(h)]
    dx = (0, -1, 1, 0)
    dy = (1, 0, 0, -1)
    que = Queue()
    que.put(s)
    while not que.empty():
        x, y = que.get()
        if visit[x][y]:
            continue

        visit[x][y] = True
        for j in range(4):
            sx = x + dx[j]
            sy = y + dy[j]
            if sx < 0 or sx >= h or sy < 0 or sy >= w:
                continue
            if tile[sx][sy] != '#':
                que.put((sx, sy))

    ans = 0
    for col in visit:
        ans += col.count(True)

    print(ans)

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    rr = []

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

    while True:
        w,h = LI()
        if w == 0:
            break
        a = [S() for _ in range(h)]
        q = []
        f = collections.defaultdict(bool)
        for i in range(h):
            for j in range(w):
                if a[i][j] == '@':
                    q.append((i,j))
        qi = 0
        while len(q) > qi:
            i,j = q[qi]
            qi += 1
            for di,dj in dd:
                ni = i + di
                nj = j + dj
                if 0 <= ni < h and 0 <= nj < w and a[ni][nj] == '.' and not f[(ni,nj)]:
                    f[(ni,nj)] = True
                    q.append((ni,nj))
        rr.append(len(q))

    return '\n'.join(map(str, rr))


print(main())

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# conding: utf

from logging import getLogger, StreamHandler, NullHandler, DEBUG, INFO
logger = getLogger(__name__)
#handler = StreamHandler()
handler = NullHandler()
logger.setLevel(DEBUG)
handler.setLevel(DEBUG)
logger.addHandler(handler)
logger.propagate = False

g_field = []
g_count = 0
g_W = -1
g_H = -1

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

def dfs(x, y):
    global g_field
    global g_count
    global g_W
    global g_H


    g_count += 1

    g_field[y][x] = "-"

    for dx, dy in OFFSETS:
        logger.debug("diff: {} {}".format(dx, dy))
        new_x = x + dx
        new_y = y + dy

        if new_x < 0 or new_x >= g_W:
            continue
        if new_y < 0 or new_y >= g_H:
            continue
        new_tile = g_field[new_y][new_x]
        if new_tile == "#" or new_tile == "-":
            continue

        logger.debug("{}, {}".format(new_x, new_y))
        dfs(new_x, new_y)


if __name__ == "__main__":
    while True:
        g_W, g_H = [int(s) for s in input().strip().split()]

        if g_W == 0 and g_H == 0:
            break
        
        g_field = []
        for _ in range(g_H):
            row = list(input().strip())
            g_field.append(row)
        g_count = 0

        for y in range(g_H):
            for x in range(g_W):
                if g_field[y][x] == "@":
                    start_x = x
                    start_y = y
                    break

        dfs(start_x, start_y)

        print(g_count)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# conding: utf

from logging import getLogger, StreamHandler, NullHandler, DEBUG, INFO
logger = getLogger(__name__)
#handler = StreamHandler()
handler = NullHandler()
logger.setLevel(DEBUG)
handler.setLevel(DEBUG)
logger.addHandler(handler)
logger.propagate = False

g_field = []
g_count = 0
g_W = -1
g_H = -1

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


if __name__ == "__main__":
    while True:
        g_W, g_H = [int(s) for s in input().strip().split()]

        if g_W == 0 and g_H == 0:
            break
        
        g_field = []
        for _ in range(g_H):
            row = list(input().strip())
            g_field.append(row)
        g_count = 0

        for y in range(g_H):
            for x in range(g_W):
                if g_field[y][x] == "@":
                    start_x = x
                    start_y = y
                    break

        #dfs(start_x, start_y)
        # bfs
        queue = [(start_x, start_y)]
        
        while len(queue) > 0:
            x, y = queue.pop()

            g_count += 1
            g_field[y][x] = "-"

            for dx, dy in OFFSETS:
                logger.debug("diff: {} {}".format(dx, dy))
                new_x = x + dx
                new_y = y + dy

                if new_x < 0 or new_x >= g_W:
                    continue
                if new_y < 0 or new_y >= g_H:
                    continue
                new_tile = g_field[new_y][new_x]
                if new_tile == "#" or new_tile == "-":
                    continue
                if (new_x, new_y) in queue:
                    continue
                
                logger.debug("{}, {}".format(new_x, new_y))
                queue.append((new_x, new_y))

        print(g_count)

Submission status: Accepted

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

	pp = [1,-1,0,0]
	qq = [0,0,1,-1]
	m = []
	for i in range(y):
		m.append(list(input()))
		if '@' in m[-1]:
			ss = m[-1].index('@')
			tt = i
	cnt = 0

	def move (cx,cy):
		global cnt
		if cy >= y or cy < 0 or cx >= x or cx < 0:
			return
		if m[cy][cx] == '.' or  m[cy][cx] == '@':
			cnt += 1
			m[cy][cx] = '0'
			for i in range(4):
				move(cx + pp[i],cy + qq[i])
	move(ss,tt)
	print(cnt)