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:
def location(field, wanted):
    for i, row in enumerate(field):
        for j, cell in enumerate(row):
            if cell == wanted:
                return i, j
def count(field, wanted):
    result = 0
    for row in field:
        for cell in row:
            if cell == wanted:
                result += 1
    return result
def neighborhood(center, w, h):
    i, j = center
    return filter(lambda x: 0 <= x[0] and x[0] < h and 0 <= x[1] and x[1] < w,
                  [                (i - 1, j    ),
                   (i    , j - 1),                 (i    , j + 1),
                                   (i + 1, j    )])
printed_later = []
while True:
    #入力
    w, h = map(int, input().split())
    if(w == 0 and h == 0):
        break
    field = []  # strの配列すなわちcharの配列の配列 '.':黒 '#':赤 '@':スタート (',':到達可能)
    for i in range(h):
        field.append(list(input()))
    #出力　幅優先探索
    queue = [location(field,'@')]
    field[queue[0][0]][queue[0][1]] = ','
    while len(queue) > 0:
        for cell in neighborhood(queue.pop(0), w, h):
            if field[cell[0]][cell[1]] == '.':
                queue.append(cell)
                field[cell[0]][cell[1]] = ','
    printed_later.append(count(field, ','))
for line in printed_later:
    print(line)

Submission status: Accepted

Solution code:
from queue import *


d = [(1,0),(0,1),(-1,0),(0,-1)]
temp={}

while True:
    W,H = (int(x) for x in input().split())
    mmap=[]
    visited=[]
    flag=0
    count=1
    
    q = Queue()
    
    if W==0 & H==0:
        break
    for i in range(0,H):
        mmap.append(list(input()))
    for i in range (0,H):
        for j in range(0,W):
            if mmap[i][j] == '@':
                start=[i,j]
    
    q.put(start)
    visited.append(list(start))
    while not q.empty():
        now = q.get()
        for myd in d:
            now2 = list(now)
            now2[0] += myd[0]
            now2[1] += myd[1]
            if not(now2[0]==-1 or now2[0]==H or now2[1]==-1 or now2[1]==W) :
                if mmap[now2[0]][now2[1]] != '#' :
                    flag=0
                    for v in visited:
                        if now2 == v :
                            flag=1
                            break
                    if flag==0:
                        count+=1
                        q.put(now2)
                        visited.append(list(now2))
    
    print(count)

Submission status: Accepted

Solution code:
from collections import deque

dx,dy = [1,0,-1,0],[0,1,0,-1]

while True:
	w,h = map(int,input().split())
	if w == 0 and h == 0:
		break
	field = [input() for i in range(h)]
	for i in range(h):
		if '@' in field[i]:
			sx,sy = i,field[i].find('@')
	visited = [[False for i in range(w)] for j in range(h)]
	que = deque()
	que.append((sx,sy))
	visited[sx][sy] = True
	while que:
		p = que.popleft()
		for i in range(4):
			nx,ny = p[0] + dx[i],p[1] + dy[i]
			if 0 <= nx < h and 0 <= ny < w and field[nx][ny] != '#' and not visited[nx][ny]:
				visited[nx][ny] = True
				que.append((nx,ny))
	cnt = 0
	for i in range(h):
		for j in range(w):
			cnt += visited[i][j]
	print(cnt)

Submission status: Accepted

Solution code:
from collections import defaultdict
def explore(now,cnt):
    if cnt>W*H:#理論的にはW*H以下で全部回れるので
        a=0 #無駄なコード
    else:
        d[now]=1
        if now[1]+1<W:
            if not data[now[0]][now[1]+1]=="#":
                if not (now[0],now[1]+1) in d.keys():
                    explore((now[0],now[1]+1),cnt+1)
        if now[0]+1<H:
            if not data[now[0]+1][now[1]]=="#":
                if not (now[0]+1,now[1]) in d.keys():
                    explore((now[0]+1,now[1]),cnt+1)
        if now[0]-1>=0:
            if not data[now[0]-1][now[1]]=="#":
                if not (now[0]-1,now[1]) in d.keys():
                    explore((now[0]-1,now[1]),cnt+1)
        if now[1]-1>=0:
            if not data[now[0]][now[1]-1]=="#":
                if not (now[0],now[1]-1) in d.keys():
                    explore((now[0],now[1]-1),cnt+1)
    
while True:
    W,H=map(int,input().split())
    if W==0 and H==0:
        break
    data=[list(input()) for _ in range(H)]
    d=defaultdict()
    for i in range(H):
        for j in range(W):
            if data[i][j]=="@":
                start=(i,j)
                break
    now=start
    cnt=0
    explore(now,cnt)
    print(len(d.keys()))

Submission status: Accepted

Solution code:
while True:
    W, H = map(int, input().split())
    if W == 0 and H == 0:
        break
    maze = []
    for _ in range(H):
        maze.append(list(input()))
    visited = [[False] * W for _ in range(H)]
    dxy = [(1, 0), (0, 1), (-1, 0), (0, -1)]
    ans = 0


    def rec(x, y):
        global ans
        visited[x][y] = True
        ans += 1
        for (dx, dy) in dxy:  # 4方向の移動を試す
            x2 = x + dx
            y2 = y + dy
            if 0 <= x2 < H and 0 <= y2 < W:
                if maze[x2][y2] == '.':
                    if not visited[x2][y2]:
                        rec(x2, y2)  # 再帰呼び出し


    for h in range(H):
        for w in range(W):
            if maze[h][w] == '@':
                rec(h, w)
                break
        else:
            continue
        break

    print(ans)

Submission status: Accepted

Solution code:
import queue

while True :
    w,h = map(int,input().split())
    if w==0 and h ==0 :
        break
    maze = [input() for _ in range(h)]
    visited = [[-1]*w for _ in range(h)]
    for i in range(h):
        if "@"  in  maze[i]:
            x_f = i
    for i in range(w):
        if maze[x_f][i] =="@":
            y_f = i
    visited[x_f][y_f] = 1
    q = queue.Queue()
    q.put([x_f,y_f])
    cnt  = 1
    while  not q.empty():
        x,y = q.get()
        for dx,dy in [(1,0),(-1,0),(0,1),(0,-1)]:
            if 0<= x+dx < h and 0<= y+dy < w:
                if visited[x+dx][y+dy] == -1 and maze[x+dx][y+dy]=='.':
                    cnt += 1
                    visited[x+dx][y+dy] = 1
                    q.put([x+dx,y+dy])
    print(cnt)

Submission status: Accepted

Solution code:
from collections import deque

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

while True:
    W, H = map(int, input().split())
    if W == 0 and H == 0:
        break
    
    sx = -1
    sy = -1
    mat = [[None for _ in range(W)] for _ in range(H)]
    for i in range(H):
        s = input()
        for j in range(W):
            if s[j] == "@":
                sx = j
                sy = i
            mat[i][j] = s[j]
    
    ans = 0
    q = deque()
    q.append((sx, sy))
    while q:
        (cx, cy) = q.popleft()
        ans += 1
        for dx, dy in dxy:
            nx = cx + dx
            ny = cy + dy
            if 0 <= nx < W and 0 <= ny < H:
                if mat[ny][nx] == ".":
                    mat[ny][nx] = "#"
                    q.append((nx, ny))
    print(ans)

Submission status: Accepted

Solution code:
import queue
dxy=[(1,0),(0,1),(-1,0),(0,-1)]
def bfs(sx,sy,H,W):#幅優先探索
    q=queue.Queue()
    visited=[[False]*W for _ in range(H)]
    q.put((sx,sy))
    visited[sx][sy]=True
    ans=1
    while not q.empty():
        px,py=q.get()
        for dx,dy in dxy:
            nx=px+dx
            ny=py+dy
            if 0<=nx<H and 0<=ny<W:
                if c[nx][ny]=='.' and visited[nx][ny]==False:
                    visited[nx][ny]=True
                    q.put((nx,ny))
                    ans+=1
    return ans
while True:
    W,H=map(int,input().split())
    if(W==0 and H==0):
        break
    c=[input() for _ in range(H)]
    for i in range(H):
        if "@" in c[i]:
            sx=i
            sy=c[i].index("@")
    print(bfs(sx,sy,H,W))

Submission status: Accepted

Solution code:
from collections import deque
while 1:
    W,H = map(int,input().split())
    if W==0 and H==0:break
    tizu = []
    for i in range(H):
        row = input()
        if "@" in row:
            start = (i,row.index("@"))#h,w の順
        tizu.append(row)
    went = [[False]*W for i in range(H)]
    went[start[0]][start[1]] = True
    ans = 1
    queue = deque()#append,popleft
    queue.append(start)
    while queue:
        curh,curw = queue.popleft()
        for dh,dw in ((0,1),(0,-1),(1,0),(-1,0)):
            newh = curh + dh
            neww = curw + dw
            if 0<=newh<H and 0<=neww<W:
                if tizu[newh][neww] == "." and not went[newh][neww]:
                    went[newh][neww] =True
                    queue.append((newh,neww))
                    ans += 1
    print(ans)

Submission status: Accepted

Solution code:
def dfs(x, y, W, H):
    if x >= H or y >= W or x < 0 or y < 0:
        return
    if visited[x][y] == 1:
        return
    if gridgraph[x][y] == '.' or gridgraph[x][y] == '@':
        visited[x][y] = 1
        dfs(x+1, y, W, H)
        dfs(x, y+1, W, H)
        dfs(x-1, y, W, H)
        dfs(x, y-1, W, H)
    if gridgraph[x][y] == '#':
        return

    return


while True:
    W, H = map(int, input().split())
    if W == 0 and W == 0:
        break
    gridgraph = [list(input()) for _ in range(H)]

    visited = [[0]*W for _ in range(H)]

    sx = -1
    sy = -1
    for i, row in enumerate(gridgraph):
        for j in range(len(row)):
            if row[j] == '@':
                sx = i
                sy = j
    dfs(sx, sy, W, H)

    ans = 0
    for row in visited:
        ans += sum(row)
    print(ans)

Submission status: Accepted

Solution code:
from collections import deque

def solve(W, H, field):
    dire = [(1,0), (0,1), (-1,0), (0,-1)]
    for i in range(H):
        for j in range(W):
            if (field[i][j]=="@"):
                s = (i,j)
    check = [[0]*W for i in range(H)]
    q = deque()
    q.append(s)
    check[s[0]][s[1]] = 1
    ret = 1
    while q:
        y, x = q.popleft()
        for dy, dx in dire:
            if (y+dy<H) and (y+dy>=0) and (x+dx<W) and (x+dx>=0):
                if (field[y+dy][x+dx] == ".") and (not check[y+dy][x+dx]):
                    q.append((y+dy, x+dx))
                    check[y+dy][x+dx] = 1
                    ret += 1
    return ret

def main():
    ans = []
    while True:
        W, H = list(map(int, input().split()))
        if (not W) and (not H):
            break
        field = [input() for i in range(H)]
        ans.append(solve(W, H, field))
    for i in ans:
        print(i)
    
main()

Submission status: Accepted

Solution code:
def main():
    while 1:
        w, h = map(int, input().split())
        if w == 0: break
        fld = [[] for i in range(h)]
        for i in range(h):
            readline = input()
            for j in range(w):
                item = readline[j]
                fld[i].append(item)
                if item == '@': sy, sx = i, j
        solve(fld, sy, sx)
        count = 0
        for i in range(h):
            for j in range(w):
                if fld[i][j] == 'A': count += 1
        print(count)

def solve(fld, cy, cx):
    vy = [1,-1,0,0]
    vx = [0,0,1,-1]
    fld[cy][cx] = 'A'
    for i in range(4):
        ny = cy + vy[i]
        nx = cx + vx[i]
        if ny < 0 or nx < 0 or ny >= len(fld) or nx >= len(fld[0]):continue
        elif fld[ny][nx] == '.': solve(fld, ny, nx)
main()

Submission status: Accepted

Solution code:
vec = [[1,0],[0,1],[-1,0],[0,-1]]

def dfs(nw,nh):
    global count
    count += 1
    visited[nh][nw] = True
    for x,y in vec:
        new_w = nw + x
        new_h = nh + y
        if (0 <= new_w) and (new_w) < w:
            if (0 <= new_h) and (new_h) < h:
                if (lis_f[new_h][new_w] == ".") and (visited[new_h][new_w] == False):
                    dfs(new_w,new_h)
                    
while(True):
    w,h = map(int,input().split())
    if (w,h) == (0,0):
        break
    lis_f = []
    for _ in range(h):
        lis_f.append(list(input()))
    
    visited = [[False for _ in range(w)] for _ in range(h)]
    count = 0
    
    id_w = 0
    id_h = 0
    set_w = 0
    set_h = 0
    while(id_h < h):
        while(id_w < w):
            #print(lis_f[id_h][id_w])
            if lis_f[id_h][id_w] == "@":
                set_w = id_w
                set_h = id_h
            id_w += 1
        id_h += 1
        id_w = 0
    
    #print(set_w,set_h)
    
    dfs(set_w,set_h)
    print(count)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10**6)

W = None
H = None
MMAP = None
D = [(0,1),(0,-1),(1,0),(-1,0)]

def main():
    global W,H,MMAP,D
    while True:
        W,H = map(int,input().split())
        if not W and not H:
            return
        MMAP = [[] for _ in range(H)] # tiles[y][x]
        sx,sy = 0,0
        for y in range(H):
            row = list(input())
            if "@" in row:
                sy = y
                sx = row.index("@")
            MMAP[y] = row
        # gprint(tiles)
        print(calc(sx,sy))

def calc(x,y):
    global W,H,MMAP,D

    if not (x >= 0 and x < W and y >= 0 and y < H):
        return 0
    
    if MMAP[y][x] == "v" or MMAP[y][x] == "#":
        return 0

    # gprint(MMAP)
    # input()

    ssum = 1
    MMAP[y][x] = "v"

    for dx,dy in D:
        nx = x+dx
        ny = y+dy
        ssum += calc(x+dx,y+dy)

    return ssum

def gprint(tiles):
    for r in tiles:
        print(str("|".join(r)))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
move = [[0, 1], [0, -1], [1, 0], [-1, 0]]
from collections import deque
def main(w, h):
    field = [list(input()) for i in range(h)]
    check = [[True] * w for i in range(h)]
    q = deque()
    for i in range(h):
        for k in range(w):
            if field[i][k] == "@":
                q.append((k, i))
                check[i][k] = False
    ans = 1
    while q:
        x, y = q.popleft()
        for mx, my in move:
            xm = mx + x
            ym = my + y
            if 0 <= xm < w and 0 <= ym < h:
                if field[ym][xm] == "." and check[ym][xm]:
                    check[ym][xm] = False
                    q.append((xm, ym))
                    ans += 1
    print(ans)
while 1:
    w, h = map(int, input().split())
    if w == h == 0:
        break
    main(w,h)

Submission status: Accepted

Solution code:
while True:
    w,h = map(int,input().split())
    if w == 0:
        break
    around = ''
    for i in range(w + 2):
        around += '#'
    maze = [around]
    cnt = 1
    for i in range(h):
        row = '#' + input() + '#'
        maze.append(row)
        if '@' in row:
            loc = [[i + 1,row.index('@')]]
    maze.append(around)
    visted = loc
    left = True
    while left:
        next_loc = []
        for x,y in loc:
            for i,j in ([1,0],[0,1],[-1,0],[0,-1]):
                if maze[x + i][y + j] == '.' and [x + i,y + j] not in visted:
                    cnt += 1
                    next_loc.append([x + i,y + j])
                    visted.append([x + i,y + j])
            if  next_loc == []:
                print(cnt)
                left = False
                break
        loc = next_loc

Submission status: Accepted

Solution code:
from collections import deque

move = ((0,1),(1,0),(0,-1),(-1,0))

def inmap(x,y):
    if 0 <= x <= Lx-1 and 0<= y <= Ly-1:
        return True
    return False

while True:
    Lx,Ly = map(int,input().split())
    if Lx == 0:
        break
    curx= -1
    cury = -1
    orimap = [[] for _ in range(Ly)]
    for i in range(Ly):
        for j in input():
            orimap[i].append(j)
    for y in range(len(orimap)):
        for x in range(len(orimap[y])):
            if orimap[y][x] == "@":
                curx,cury = x,y
                orimap[y][x]="#"
                break
        if curx != -1:
            break
    Q = deque()
    Q.append([curx,cury])
    count = 1
    while len(Q)>0:
        curx,cury = Q.popleft()
        for dx,dy in move:
            nextx = curx + dx
            nexty = cury + dy
            if inmap(nextx,nexty):
                if orimap[nexty][nextx] != "#":
                    orimap[nexty][nextx] = "#"
                    Q.append([nextx,nexty])
                    count += 1
    print(count)

Submission status: Accepted

Solution code:
import collections
while True:
    w,h = map(int,input().split())
    if w == h == 0:
        break
    else:
        ans = 1
        L = []
        q = collections.deque()
        for i in range(h):
            s = input()
            T = []
            for j in range(w):
                if s[j] == '@':
                    T.append(0)
                    q.append([i,j])
                else:
                    T.append(s[j])
            L.append(T)
        dy_dx = [[1,0],[0,1],[-1,0],[0,-1]]
        while len(q) > 0:
            cur = q.popleft()
            for i in range(4):
                y = cur[0]+dy_dx[i][0]
                x = cur[1]+dy_dx[i][1]
                if 0 <= x < w and 0 <= y < h:
                    if L[y][x] == '.':
                        L[y][x] = L[cur[0]][cur[1]]+1
                        ans += 1
                        q.append([y,x])
        print(ans)

Submission status: Accepted

Solution code:
while True:
    w, h = map(int, input().split())
    if h == 0:
        break
    m = [list(input()) for _ in range(h)]
    sx = 0
    sy = 0
    for yi, row in enumerate(m):
        if '@' in row:
            sy = yi
            sx = row.index('@')
    def dfs(x, y):
        if x < 0 or w <= x or y < 0 or h <= y or m[y][x] == '#':
            return 0
        else:
            m[y][x] = '#'
            dy = [1, -1] + [0] * 2
            dx = [0] * 2 + [1, -1]
            return sum([dfs(x+dx[i], y+dy[i]) for i in range(4)]) + 1
    print(dfs(sx, sy))

Submission status: Accepted

Solution code:
class dfs:
    def __init__(self,W,H,m):
        self.W=W
        self.H=H
        self.m=m
        self.ans=0
        self.visited=[[False]*W for _ in range(H)]
    def trav(self,x,y):
        #print(x,y)
        self.visited[x][y]=True
        self.ans+=1
        offset=[(-1,0),(0,-1),(1,0),(0,1)]
        for dx,dy in offset:
            x2=x+dx
            y2=y+dy
            if 0<=x2<self.H and 0<=y2<self.W and self.m[x2][y2]=='.' and self.visited[x2][y2]==False:
                self.trav(x2,y2)
    

while True:
    W,H=map(int,input().split())
    if not (W and H): break
    m=[]
    for i in range(H):
        L=list(input())
        if '@' in L:
            (sx,sy)=(i,L.index('@'))
        m.append(L)
    D=dfs(W,H,m)
    D.trav(sx,sy)
    print(D.ans)

Submission status: Accepted

Solution code:
while True:
    w, h = map(int, input().split())
    if w == 0:
        break
    # タイルの情報を文字列配列として受け取る
    tile = [""] * h
    for i in range(h):
        tile[i] = input()
    # スタート地点探索
    ok = False
    for y in range(h):
        for x in range(w):
            if tile[y][x] == "@":
                s_x = x
                s_y = y
                ok = True
                break
        if ok:
            break
    # 幅優先探索
    count = 0
    check = [[s_x, s_y]]
    check_map = [[False for j in range(w)] for i in range(h)]
    while len(check) > 0:
        x, y = check.pop(0)
        if x in range(w) and y in range(h):
            if check_map[y][x] == False:
                if tile[y][x] == "." or tile[y][x] == "@":
                    check_map[y][x] = True
                    count += 1
                    check.append([x, y-1])
                    check.append([x, y+1])
                    check.append([x+1, y])
                    check.append([x-1, y])
    print(count)

Submission status: Accepted

Solution code:
from collections import deque
d = [(1,0),(-1,0),(0,1),(0,-1)]
while 1:
    w,h = map(int, input().split())
    if w == h == 0:
        break
    s = [input() for i in range(h)]
    bfs_map = [[1 for i in range(w)] for j in range(h)]
    for y in range(h):
        for x in range(w):
            if s[y][x] == "@":
                ans = 1
                q = deque()
                q.append((y,x))
                bfs_map[y][x] = 0
                while q:
                    y, x = q.popleft()
                    for dy,dx in d:
                        y_ = y+dy
                        x_ = x+dx
                        if 0 <= y_ < h and 0 <= x_ < w:
                            if bfs_map[y_][x_] and s[y_][x_] == ".":
                                ans += 1
                                bfs_map[y_][x_] = 0
                                q.append((y_,x_))
                print(ans)
                break

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
#AOJ B
from collections import deque

def bfs():
    while 1:
        W,H = map(int,input().split())
        if W == 0 and H == 0:
            break
        maze = [list(input()) for _ in range(H)]
        check = [[False for _ in range(W)] for _ in range(H)]
        #print(maze)
        dx = [1,0,-1,0]
        dy = [0,1,0,-1]
        for i in range(H):
            for j in range(W):
                if maze[i][j] == '@':
                    sx,sy = j,i
                    check[i][j] = True

        ans = 1
        que = deque()
        que.append((sx,sy))
        while que:
            x,y = que.pop()
            for i in range(4):
                nx,ny = x + dx[i],y + dy[i]

                if 0 <= nx < W and 0 <= ny < H and maze[ny][nx] == '.' and check[ny][nx] == False:
                    que.append((nx,ny))
                    check[ny][nx] = True
                    ans += 1
        print(ans)
    return

if __name__ == '__main__':
    bfs()

Submission status: Accepted

Solution code:
def f(h,w):
  global W,H,S,A
  if h<0 or h>=H or w<0 or w>=W or S[h][w]=="#" or A[h][w]==1:
    return
  A[h][w] = 1
  f(h-1,w)
  f(h+1,w)
  f(h,w-1)
  f(h,w+1)
while True:
  W,H = map(int,input().split())
  if W+H == 0:
    break
  S = [list(input()) for h in range(H)]
  A = [[0 for w in range(W)] for h in range(H)]
  for h in range(H):
    for w in range(W):
      if S[h][w] == "@":
        f(h,w)
        break
  ans = 0
  for i in A:
    ans += sum(i)
  print(ans)

Submission status: Accepted

Solution code:
c = 0
def calc(t, X, Y):
    global c
    c += 1
    t[Y][X] = '#'
    for x, y in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
        if t[Y + y][X + x] == '.':
            calc(t, X + x, Y + y)
            
while True:
    c = 0
    w, h = map(int, input().split())
    if w == h == 0:
        break
    
    t = [['#'] * (w + 2) ] + [['#'] + list(input()) + ['#'] for _ in range(h)] + [['#'] * (w + 2)]
    for sy in range(h + 2):
        if '@' in t[sy]:
            sx = t[sy].index('@')
            break
      
    calc(t, sx, sy)
    print(c)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10000)


def dfs(x, y):
    global cout
    if 0 <= x < H - 1 and tile[x + 1][y] == ".":
        cout += 1
        tile[x + 1][y] = "#"
        dfs(x + 1, y)
    if 0 < x < H and tile[x - 1][y] == ".":
        cout += 1
        tile[x - 1][y] = "#"
        dfs(x - 1, y)
    if 0 <= y < W - 1 and tile[x][y + 1] == ".":
        cout += 1
        tile[x][y + 1] = "#"
        dfs(x, y + 1)
    if 0 < y < W and tile[x][y - 1] == ".":
        cout += 1
        tile[x][y - 1] = "#"
        dfs(x, y - 1)
    return 0


def search_start():
    for i in range(H):
        for j in range(W):
            if tile[i][j] == "@":
                tile[i][j] = "#"
                return (i, j)


if __name__ == "__main__":
    while True:
        W, H = map(int, input().split())
        if W == 0 and H == 0:
            break
        # print(W, H)
        tile = [list(input()) for _ in range(H)]
        cout = 1
        start = search_start()
        # print(start)
        dfs(start[0], start[1])
        # print(*tile, sep="\n")
        # print("total count : {}".format(cout))
        print(cout)

Submission status: Accepted

Solution code:
def dfs(now,origin,drawn): # 深さ優先探索　再帰関数　originは変更しない　drawnは訪れた場所に1それ以外は0
    positive = '.' # 進める場所
    negative = '#' # 進めない場所(壁)
    direct = [0,0,0,0] # [上,下,左,右]を表す
    height = len(origin)
    width = len(origin[0])
    now_h = now[0]
    now_w = now[1]
    ### それぞれの方向について、originにおいてpositiveかつdrawnにおいて0（つまり訪れたことがある）なら進める
    if now_h != 0 and origin[now_h-1][now_w] == positive and drawn[now_h-1][now_w] == 0:
        direct[0] = 1
    if now_h != height-1 and origin[now_h+1][now_w] == positive and drawn[now_h+1][now_w] == 0:
        direct[1] = 1
    if now_w != 0 and origin[now_h][now_w-1] == positive and drawn[now_h][now_w-1] == 0:
        direct[2] = 1
    if now_w != width-1 and origin[now_h][now_w+1] == positive and drawn[now_h][now_w+1] == 0:
        direct[3] = 1

    if sum(direct) == 0: # 進む先がなければ終了
        return 0
    d = {0:[now_h-1,now_w],1:[now_h+1,now_w],2:[now_h,now_w-1],3:[now_h,now_w+1]} # 進む先の座標を辞書にしておく
    for i in range(4):
        if direct[i] == 1:
            drawn[d[i][0]][d[i][1]] = 1 # d[i]の座標に移動したのでdrawnで訪れたことを記録した
            dfs(d[i],origin,drawn) # 再帰
    return 0

while True:
    W, H = map(int,input().split()) # 入力を受け取る
    if W == 0 and H == 0: # 両方0だったらbreak
        break
    tiles = [list(input()) for i in range(H)] # 入力
    possible_tiles = [[0 for i in range(W)] for j in range(H)] # 訪れたことがある場所を記憶する
    for h in range(H):
        for w in range(W):
            if tiles[h][w] == '@': # 現在地
                now = [h,w]
                break
    possible_tiles[now[0]][now[1]] = 1 # 現在地は既に訪れている
    dfs(now,tiles,possible_tiles) # 探索
    ans = 0
    for h in range(H):
        for w in range(W):
            if possible_tiles[h][w] == 1:
                ans += 1
    print(ans)

Submission status: Accepted

Solution code:
w,h=map(int,input().split())
while w!=0 or h!=0:
    maps=[]
    flag=False
    ans=0
    for i in range(h):
        k=list(input())
        maps.append(k)
    for i in range(h):
        if flag:
            break
        for j in range(w):
            if maps[i][j]=='@':
                maps[i][j]='#'
                pos_x=i
                pos_y=j
                flag=True
                break
    def check(x,y):
        global maps
        if 0<=x<h and 0<=y<w:
            pass
        else:
            return False
        if maps[x][y]=='#':
            return False
        else:
            return True
    def bfs(x,y):
        global ans
        global maps
        for i in [[0,1],[0,-1],[1,0],[-1,0]]:
            p=i[0]
            q=i[1]
            if check(x+p,y+q):
                ans+=1
                maps[x+p][y+q]='#'
                bfs(x+p,y+q)
    bfs(pos_x,pos_y)
    print(ans+1)
    w,h=map(int,input().split())

Submission status: Accepted

Solution code:
import math

def search(w,h,data): 
    for i in range(h):
        if '@' in data[i]:
            stx,sty = i,data[i].index('@')

    stack = [[stx,sty]]
    check = [[stx,sty]]
    while True:
        if len(stack) != 0:
            s = stack[-1]
            Hnow,Wnow = s[0],s[1]
        else:
            return len(check)

        stack.pop()
        
        if Hnow < h-1:
            if (data[Hnow+1][Wnow] == '.') and ([Hnow+1,Wnow] not in check):
                stack.append([Hnow+1,Wnow])
                check.append([Hnow+1,Wnow])

        if Wnow < w-1:
            if (data[Hnow][Wnow+1] == '.') and ([Hnow,Wnow+1] not in check):
                stack.append([Hnow,Wnow+1])
                check.append([Hnow,Wnow+1])

        if Hnow > 0:
            if (data[Hnow-1][Wnow] == '.') and ([Hnow-1,Wnow] not in check):
                stack.append([Hnow-1,Wnow])
                check.append([Hnow-1,Wnow])

        if Wnow > 0:
            if (data[Hnow][Wnow-1] == '.') and ([Hnow,Wnow-1] not in check):
                stack.append([Hnow,Wnow-1])
                check.append([Hnow,Wnow-1])

a = []


while True:
    w,h = list(map(int,input().split()))
    if (w == 0)and(h == 0):
        break
    else:
        data = [list(input()) for l in range(h)]
        a.append(search(w,h,data))

for i in a:
    print(i)

Submission status: Accepted

Solution code:
# coding: utf-8
def check(p):
    global ans
    global field
    ans+=1
    if(field[p[1]][p[0]]=='.'):
        field[p[1]][p[0]]='#'
    if(0<=p[0]+1<w and field[p[1]][p[0]+1]=='.'):
        check((p[0]+1,p[1]))
    if(0<=p[0]-1<w and field[p[1]][p[0]-1]=='.'):
        check((p[0]-1,p[1]))
    if(0<=p[1]+1<h and field[p[1]+1][p[0]]=='.'):
        check((p[0],p[1]+1))
    if(0<=p[1]-1<h and field[p[1]-1][p[0]]=='.'):
        check((p[0],p[1]-1))
    
    
while 1:
    ans=0
    w,h=map(int,input().split())
    if w==0:
        break
    field=[]
    for i in range(h):
        s=input()
        t=s.find('@')
        if(t!=-1):
            st=(t,i)
        field.append(list(s))
    check(st)
    print(ans)

Submission status: Accepted

Solution code:
def solve(dat):
    H = len(dat)
    W = len(dat[0])

    for i in range(H):
        for j in range(W):
            if dat[i][j] == "@":
                si, sj = i, j

    tmp = [[0 for _ in range(W)] for _ in range(H)]
    di = [-1,1,0,0]
    dj = [0,0,-1,1]
    pool = [(si, sj)]

    while len(pool) > 0:
        # print pool, i, j
        i, j = pool.pop()
        tmp[i][j] = 1
        for k in range(4):
            ni = i + di[k]
            nj = j + dj[k]
            if ni in range(H) and nj in range(W) and dat[ni][nj] == "." and tmp[ni][nj] == 0:
                pool.append((ni, nj))
    cnt = sum([sum(tmp[i]) for i in range(H)])
    return cnt


while True:
    W, H = map(int, raw_input().split(" "))
    if W == H == 0:
        break
    dat = [raw_input() for _ in range(H)]
    print solve(dat)

Submission status: Runtime Error

Solution code:
def search(x, y, m):
    if 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))