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 search(a,b,dx,dy,t,check,li,answer):
    for i in range(len(dx)):
            temp = [t[0]+dx[i],t[1]+dy[i]]
            if mapCheck(a,b,temp):
                if check[temp[1]][temp[0]] == 0:
                    if li[temp[1]][temp[0]] == '.':
                        answer += 1
                        check[temp[1]][temp[0]] = 1
                        answer = search(a,b,dx,dy,temp,check,li,answer)
    return answer
                    
                
            
def mapCheck(a,b,t):
    if t[0] <= a-1 and t[0] >=0:
        if t[1] <= b-1 and t[1] >= 0:
            return True
    return False

while True:
    li = []
    answer = 1
    start = [0,0]
    a,b = map(int, input().strip().split(' '))
    dx = [1,0,-1,0]
    dy = [0,1,0,-1]
    if a == 0 and b == 0:
        break
    for i in range(b):
        li.append(input().strip().split())
    check = [[0 for i in range(a)] for j in range(b)]
    for i in range(len(li)):
        li[i] = str(li[i])
        li[i] = list(li[i])
        del li[i][0]
        del li[i][0]
        del li[i][len(li[i])-1]
        del li[i][len(li[i])-1]
        for j in range(len(li[i])):
            if li[i][j] == '@':
                start = [j,i]
    print(search(a,b,dx,dy,start,check,li,answer))

Submission status: Accepted

Solution code:
def fill(y,x):
    global l,c,w,h
    if 0<=x+1<w and 0<=y<h and l[y][x+1]==".":
        c+=1
        l[y][x+1]=1
        fill(y,x+1)
    if 0<=x-1<w and 0<=y<h and l[y][x-1]==".":
        c+=1
        l[y][x-1]=1
        fill(y,x-1)
    if 0<=x<w and 0<=y+1<h and l[y+1][x]==".":
        c+=1
        l[y+1][x]=1
        fill(y+1,x)
    if 0<=x<w and 0<=y-1<h and l[y-1][x]==".":
        c+=1
        l[y-1][x]=1
        fill(y-1,x)
    return c

while 1:
    w,h=map(int,input().split())
    if not w and not h:break
    l=[list(input()) for _ in range(h)]
    y,x=[[n,i.index("@")] for (n,i) in enumerate(l) if "@" in i][0]
    l[y][x]=1
    c=1
    print(fill(y,x))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
#rea and blac
h,w=1,1

count=0

def search(x,y):
    #マップの外側か壁の場合は何もしない
    #print(x,y)
    global count
    if x<0 or x>w-1 or y<0 or y>h-1 or map_data[y][x]=='#':
 
        return
        
    
    #以前に到達していたら何もしない
    if reached[y][x]:
         return

    reached[y][x]=1
    count+=1
    #print("aa")



    search(x+1,y)#右
    search(x-1,y)#左
    search(x,y+1)#上
    search(x,y-1)#下
    



while h!=0 and w!=0: 

    count=0
    #グラフの入力方法------

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

    map_data = [[0]*w for _ in range(h)]
    reached = [[0]*w for _ in range(h)]
    for i in range(h):
        ct = raw_input()
        #print(len(ct))
        for j in range(w):
            map_data[i][j] = ct[j]
            if ct[j]=="@":
                sx=j
                sy=i

    #------



    search(sx,sy)

    print(count)
    count=0
    w=1
    h=1

Submission status: Accepted

Solution code:
def walk(x, y):
        #print x,y
        global s
        global c
        global v
        if 0 <= x < w and 0 <= y < h:
                if v[y][x] is False:
                        if s[y][x] == '@' or s[y][x] == '.':
                                v[y][x] = True
                                c += 1
                                #print 'hai'
                                walk(x-1, y)
                                walk(x, y-1)
                                walk(x+1, y)
                                walk(x, y+1)

while 1:
        c = 0
        w,h = map(int, raw_input().split())
        if w == 0 and h == 0: break
        s = ['' for i in xrange(h)]
        v = [[False for j in xrange(w)] for i in xrange(h)]
        for i in xrange(h):
                s[i] = raw_input()
        for i in xrange(w):
                for j in xrange(h):
                        if s[j][i] == '@':
                                walk(i, j)
        #print v
        print c

Submission status: Accepted

Solution code:
import sys
import collections

x = [1, 0, -1, 0]
y = [0, 1, 0, -1]
while True:
    W, H = map(int, sys.stdin.readline().split())
    if W == 0:
        break
    
    tile = [[0 for i in xrange(W + 2)] for j in xrange(H + 2)]
    
    visited = set()
    next = set()
    
    for i in xrange(H):
        line = raw_input().strip()
        for j in xrange(W):
            if line[j] == '.':
                tile[i + 1][j + 1] = 1
            if line[j] == '@':
                tile[i + 1][j + 1] = 1
                next.add((i + 1, j + 1))
#    for line in tile:
#        print line
    while len(next) > 0:
        temp_next = set()
        for n in next:
            visited.add(n)
            for i in xrange(4):
                temp = (n[0] + x[i], n[1] + y[i])
                if temp not in visited and tile[temp[0]][temp[1]] == 1:
                    temp_next.add(temp)
        next = temp_next
    print len(visited)

Submission status: Accepted

Solution code:
mv=((0,1),(0,-1),(1,0),(-1,0))

def dfs(y,x):
    global cnt
    L[y][x]=""
    cnt+=1
    for i,j in mv:
        mx=x+i
        my=y+j
        if 0<=mx<W and 0<=my<H and L[my][mx]==".":
            dfs(my,mx)

while True:
    W,H=map(int,raw_input().split())
    if W==H==0:break
    cnt=0
    L=[list(raw_input()) for i in range(H)]
    for i in range(H):
        for j in range(W):
            if L[i][j]=="@":
                x,y=j,i
    dfs(y,x)
    print cnt

Submission status: Accepted

Solution code:
dx = [-1,0,1,0]; dy = [0,-1,0,1];
while 1:
    w,h = map(int, raw_input().split())
    if w==h==0: break;
    m = []; s = []; sx = sy = 0;
    m.append('#'*(w+2))
    for i in range(h):
        m.append("#"+raw_input()+"#")
    m.append('#'*(w+2))
    f = [[0 for i in range(w+2)] for j in range(h+2)]
    for i in range(1,h+1):
        for j in range(1,w+1):
            if m[i][j]=='@':
                sx = j; sy = i;
    s.append([sx,sy]);
    f[sy][sx] = 1; ans = 1;
    while len(s)>0:
        x,y = s.pop(0)
        for k in range(4):
            if m[y+dy[k]][x+dx[k]]!='#' and f[y+dy[k]][x+dx[k]]==0:
                s.append([x+dx[k],y+dy[k]])
                f[y+dy[k]][x+dx[k]] = 1; ans += 1;
    print ans

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

count = 0
def dfs(i, j, island):
    global count
    #print i, j
    dxy = [(1, 0), (0, 1), (-1, 0), (0, -1)]
    
    if i < 0 or i >= len(island) or j < 0 or j >= len(island[0]):
        return

    if island[i][j] == '#' or island[i][j] == 'x':
        return

    island[i][j] = 'x'
    count += 1
    
    for d in dxy:
        dfs(i+d[0], j+d[1], island)

def solve(w, h, island):
    s_i = 0
    s_j = 0
    for i, row in enumerate(island):
        for j, s in enumerate(row):
            if s == '@':
                s_i = i
                s_j = j
                break

    dfs(s_i, s_j, island)
    print count

def func():
    '''

    '''
    while True:
        global count
        wh = map(int, raw_input().split())
        w = wh[0]
        h = wh[1]
        if w == 0 and h == 0:
            break
        island = []
        count = 0
        for i in range(h):
            row = []
            line = raw_input()
            for j in line:
                row.append(j)
            island.append(row)
        
        # for row in island:
        #     for j in row:
        #         print j
        #     print ''

        solve(w, h, island)


func()

Submission status: Accepted

Solution code:
def solve(w,h):
	if 0 <= w < W and 0 <= h < H and tile[h][w] == ".":
		tile[h][w] = 0
		solve(w+1,h); solve(w,h+1); solve(w-1,h); solve(w,h-1)
while 1:
	W,H = map(int,raw_input().split())
	if W == 0: break
	tile = [list(raw_input()) for i in range(H)]
	for h in range(H):
		try:
			sw = tile[h].index("@")
			sh = h
			tile[sh][sw] = "."
			break
		except:
			pass
	solve(sw,sh)
	print sum(tile[h].count(0) for h in range(H))

Submission status: Accepted

Solution code:
"""
1. スタート地点の座標を取得
2. スタート地点からbfsをして到達可能な”.”の数を数える
"""

from collections import deque

def bfs(h, w, f, s):
    count = 1
    q = deque()
    q.append(s)

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

    while q:
        i, j = q.popleft()

        for di, dj in move:
            ni , nj = i + di, j + dj
            if 0 <= ni < w and 0 <= nj < h and f[ni][nj] == ".":
                count += 1
                q.append((ni, nj))
                f[ni][nj] = "#"

    return count

def search_atmark(h, w, f):
    for i in range(h):
        for j in range(w):
            if f[i][j] == "@":
                return (i, j)

def solve(h, w, f):
    s = search_atmark(w, h, f)
    return bfs(h, w, f, s)

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

        f = [list(input()) for i in range(h)]
        print(solve(w, h, f))

Submission status: Accepted

Solution code:
#2:52
import sys

sys.setrecursionlimit(10000000)


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



#左上からせめて深さ優先で探索する問題
while True:
    # 地図作る
    width,hight = map(int,input().split())
    if width ==0 :
        break
    d =[]
    for _ in range(hight):
        d.append(list(input()))
    
    def dfs(x, y):
    # いまたどり着いたはずなので1に塗りつぶす
        d[y][x]="d"

    #4方向ループ
    #あくまで方向の表し方dxは
        for i in range(4):
            ny = y + dx[i]
            nx = x + dy[i]

        #行ったことがなくって、迷路の範囲内で、障害物がなければ、進む
            if 0 <= ny and ny < hight \
              and 0 <= nx and nx < width \
              and d[ny][nx] == ".":
                dfs(nx,ny) 

    


    for y in range(hight):
        for x in range(width):
            if d[y][x] == "@":
                dfs(x,y)
    
    sum = 0 
    for _ in range(hight):
        sum = sum + d[_].count('d')
    print(sum)

Submission status: Accepted

Solution code:
from collections import deque

while True:
    W, H = map(int, input().split())
    if W | H == 0:
        break
    tiles = [input() for i in range(H)]
    first = ()
    for h in range(H):
        index = tiles[h].find("@")
        if index != -1:
            first = (index, h)
            break
    memo = {first: 0}
    que = deque([first])
    count = 1
    while len(que) > 0:
        x, y = que.popleft()
        for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
            if (x + dx, y + dy) not in memo:
                if (0 <= x + dx < W) and (0 <= y + dy < H) and tiles[y + dy][x + dx] == ".":
                    count += 1
                    memo[(x + dx, y + dy)] = 1
                    que.append((x + dx, y + dy))
    print(count)

Submission status: Accepted

Solution code:
def solve(w,h,tile):
    # スタート地点探索
    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])
    return count

while True:
    try:
        w, h = map(int, input().split())
        if w == 0:
            break
        tile = [""] * h
        for i in range(h):
            tile[i] = input()

        print(solve(w,h,tile))
    except:
        break

Submission status: Accepted

Solution code:
#演習2-22
def solve(w,h,tile):
    # スタート地点探索
    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])
    return count

while True:
    try:
        w, h = map(int, input().split())
        if w == 0:
            break
        tile = [""] * h
        for i in range(h):
            tile[i] = input()

        print(solve(w,h,tile))
    except:
        break

Submission status: Accepted

Solution code:
import collections
while True:
    w,h = map(int,input().split())
    if w==0 and h==0:
        break
    tile=[]
    tile.append(["#"]*(w+2))
    for _ in range(h):
        temp= list(input())
        temp=  ["#"]+ temp + ["#"]
        tile.append(temp)
    tile.append(["#"]*(w+2))

    route=[[[0,0,0,0] for i in range(w)] for j in range(h)]
    for i in range(1,h+1):
        for j in range(1,w+1):
            if tile[i+1][j] ==".":
                route[i-1][j-1][0]= 1
            if tile[i-1][j] ==".":
                route[i-1][j-1][1]= 1
            if tile[i][j+1] ==".":
                route[i-1][j-1][2]= 1
            if tile[i][j-1] ==".":
                route[i-1][j-1][3]= 1
            if tile[i][j]=="@":
                st=[i-1,j-1]

    dir= [[1,0],[-1,0],[0,1],[0,-1]]
    d=[[0]*w for i in range(h)]
    d[st[0]][st[1]]=1
    q= collections.deque()
    q.append(st)
    while len(q)> 0:
        cur = q.popleft()
        for i in range(4):
            if route[cur[0]][cur[1]][i]==1 and d[cur[0]+dir[i][0]][cur[1]+dir[i][1]]==0:
                d[cur[0]+dir[i][0]][cur[1]+dir[i][1]]=1
                q.append([cur[0]+dir[i][0],cur[1]+dir[i][1]])

    ans=0
    for i in range(h):
        for j in range(w):
            if d[i][j] == 1:
                ans+=1
    print(ans)

Submission status: Accepted

Solution code:
import collections

dx = [-1,0,1,0]
dy = [0,-1,0,1]
def movable(dst):
    if dst[0]<0 or dst[0]>b-1:
        return False
    elif dst[1]<0 or dst[1]>a-1:
        return False
    elif MM[dst[0]][dst[1]] == '#':
        return False
    else:
        return True

while True:
    c = 1
    a,b = map(int,input().split())
    if a==0 and b==0:
        exit()
    else:
        MM = []
        for i in range(b):
            q = list(input())
            MM.append(q)
            if '@' in q:
                st = [i, q.index('@')]

        D = [[-1 for _ in range(a)] for _ in range(b)]
        D[st[0]][st[1]] = 0 # 始点への距離は 0, 他の距離は-1
        Q = collections.deque()
        Q.append(st) # 始点
        while len(Q) > 0:
            #print("bfs", Q) # 各ステップでの Q の動作を確認
            cur = Q.popleft()
            for dir in range(4):
                # curからdstに移動可能かつ、dstが未訪問だったら
                dst = [cur[0]+dx[dir], cur[1]+dy[dir]]
                #print(dst)
                if movable(dst) and D[dst[0]][dst[1]] == -1:
                    D[dst[0]][dst[1]] = D[cur[0]][cur[1]]+1
                    c += 1
                    Q.append(dst) # Qにdstを詰める
        print(c)

Submission status: Accepted

Solution code:
x=0
y=0
b=[]
t=[]
dir=[[1,0],[0,1],[-1,0],[0,-1]]
ans=0

def dfs(p_x,p_y):
  global b,t,ans
  if t[p_y][p_x] or not b[p_y][p_x]: return
  ans+=1
  t[p_y][p_x]=True
  for i in dir:
    dfs(p_x+i[0],p_y+i[1])

while True:
  x=0
  y=0
  w,h=map(int,input().split())
  if w==0 and h==0: break
  b=[[False]*(w+2) for i in range(h+2)]
  t=[[False]*(w+2) for i in range(h+2)]
  ans=0
  for i in range(1,h+1):
    tmp=list(input())
    for j in range(1,w+1):
      b[i][j]=(tmp[j-1] in {'.','@'})
      if tmp[j-1]=='@': x=j;y=i
  dfs(x,y)
  print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10000000)
MOD = 10 ** 9 + 7
INF = 10 ** 15
Dy = (-1,0,1,0)
Dx = (0,1,0,-1)

from collections import deque,defaultdict,Counter
def solve(H,W):
    grid = [input() for _ in range(H)]
    cnt = [[0]*W for _ in range(H)]
    for i in range(H):
        for j in range(W):
            if grid[i][j] == '@':
                sy,sx = i,j
                break
    
    q = deque([(sy,sx)])
    cnt[sy][sx] = 1
    ans = 1
    while q:
        ny,nx = q.popleft()
        for dy,dx in zip(Dy,Dx):
            y = ny + dy
            x = nx + dx
            if y < 0 or y >= H:
                continue
            if x < 0 or x >= W:
                continue
            if grid[y][x] == '#':
                continue
            if cnt[y][x] == 1:
                continue
            cnt[y][x] = 1
            ans += 1
            q.append((y,x))
    print(ans)
    
def main():
    while True:
        W,H = map(int,input().split())
        if H == 0 and W == 0:
            return
        solve(H,W)
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque

ans = []
while True:
    w, h = map(int, input().split())
    if not w and not h:
        break
    
    roadmap = []
    d = deque()
    able = [[False for i in range(w)] for j in range(h)]
    for i in range(h):
        roadmap.append(input())
        
    
    for i in range(h):
        for j in range(w):
            if roadmap[i][j] == '@':
                able[i][j] = True
                d.append([i, j])

    
    while len(d):
        y, x = d.pop()
        
        for course in [[0, 1], [1, 0], [-1, 0], [0, -1]]:
            tmpy, tmpx = y + course[0], x + course[1]
            if tmpy < 0 or tmpy >= h or tmpx < 0 or tmpx >= w:
                continue
                
            if not able[tmpy][tmpx] and roadmap[tmpy][tmpx] == '.':
                able[tmpy][tmpx] = True
                d.append([tmpy, tmpx])

    a = 0
    for i in range(h):
        a += len(list(filter(lambda x:x, able[i])))

    ans.append(a)

[print(i) for i in ans]

Submission status: Accepted

Solution code:
def Check(A, i, j, W, H) :
    if j-1 >= 0 :
        if A[i][j-1] == "." :
            A[i][j-1] = "+"
            Check(A, i, j-1, W, H)
    if i+1 < H :
        if A[i+1][j] == "." :
            A[i+1][j]= "+"
            Check(A, i+1, j, W, H)
    if j+1 < W :
        if A[i][j+1] == "." :
            A[i][j+1] = "+"
            Check(A, i, j+1, W, H)
    if i-1 >= 0 :
        if A[i-1][j] == "." :
            A[i-1][j] = "+"
            Check(A, i-1, j, W, H)
    return(A)

while True :
    W, H = map(int, input().split())
    if W == 0 and H == 0 :
        break
    
    Tile = [list(input()) for i in range(H)]
    for i in range(H) :
        for j in range(W) :
            if Tile[i][j] == "@" :
                my_i = i
                my_j = j
    Tile[my_i][my_j] = "+"
    Tile_new = Check(Tile, my_i, my_j, W, H)
    count = 0
    for i in range(H) :
        for j in range(W) :
            if Tile_new[i][j] == "+" :
                count += 1
    print(count)

Submission status: Accepted

Solution code:
from collections import deque
def bfs():
    d = [[False] * w for i in range(h)]
    dx = [1,0,-1,0]
    dy = [0,1,0,-1]

    que = deque([])
    que.append((sx,sy))
    d[sx][sy] = True
    cnt = 1

    while que:
        p = que.popleft()
        for i in range(4):
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]

            if 0 <= nx < h and 0 <= ny < w and Map[nx][ny] != "#" and d[nx][ny] == False:
                cnt += 1
                que.append((nx,ny))
                d[nx][ny] = True
    return cnt

while 1:
    w,h = map(int,input().split())
    if w == 0 and h == 0:
        break
    Map = [str(input()) for i in range(h)]
    for i in range(h):
        for j in range(w):
            if Map[i][j] == "@":
                sx = i
                sy = j
    print(bfs())

Submission status: Accepted

Solution code:
from collections import deque

y = [-1,0,1,0]
x = [0,-1,0,1]

def main():

    h,w = 0,0
    c = []

    def check(i,j):
        return 0<=i and i<h and 0<=j and j<w

    def bfs(a,b):
        res = 0
        d = deque()
        d.append([a,b])
        f = [[False]*w for _ in range(h)]
        while len(d):
            i,j = d.popleft()
            if not check(i,j):continue
            if c[i][j]=='#':continue
            if f[i][j]==True:continue
            res += 1
            f[i][j]=True
            for k in range(4):
                d.append([i+y[k],j+x[k]])
        return res

    while True:
        w,h = map(int,input().split())
        if h==0 and w==0:break
        c = []
        for i in range(h):
            c.append(input())
        res = 0
        for i in range(h):
            for j in range(w):
                if c[i][j]=='@':
                    res = bfs(i,j)
        print(res)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
dxy = [[1,0],[-1,0],[0,1],[0,-1]]
n=0
def rec(x,y):
    global n
    if (x<0 or x>=h or y<0 or y>=w) or (visited[x][y] or tile[x][y]!='.'):
        return 0
    visited[x][y] = True
    n += 1
    for (dx,dy) in dxy:
        x2 = x + dx
        y2 = y + dy
        rec(x2,y2)
    return 0

w,h=map(int,input().split())
ans = []
while((w,h)!=(0,0)):
    n=0
    tile = []
    for _ in range(h):
        tile.append(list(input()))
    visited = [[False] * w for _ in range(h)]
    for a in range(h):
        for b in range(w):
            if(tile[a][b]=='@'):
                pos_x = a
                pos_y = b
                tile[a][b]='.'
    rec(pos_x, pos_y)
    ans.append(n)
    w,h=map(int,input().split())
for a in ans:
    print(a)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
'''
所要時間は、分位であった。
'''


# ライブラリのインポート
#import re #正規表現
import sys
input = sys.stdin.readline
#import heapq
#import bisect
#import collections
#import math
#from pprint import pprint

def main():
    while 1:
        w, h = map(int, input().split())
        if w == 0 and h == 0: break
        mp = []
        for i in range(h):
            mp.append(list(input().strip()))
            if "@" in mp[-1]:
                stj = mp[-1].index("@")
                sti = i
        flag = [[0]*w for i in range(h)]
        #pprint(flag)
        flag = dfs(sti, stj, flag, mp)
        ans = sum([flag[i].count(1) for i in range(h)])
        print(ans)
        #pprint(flag)
def dfs(rw, cm, flag, mp):
    flag[rw][cm] = 1
    #print(rw,cm)
    #pprint(flag)
    try:
        c = mp[rw][cm-1]
        b = flag[rw][cm-1]
    except: c = "#"
    if c == "." and b == 0 and rw>=0 and cm>0: dfs(rw, cm-1, flag, mp)
    try:
        c = mp[rw-1][cm]
        b = flag[rw-1][cm]
    except: c = "#"
    if c == "." and b == 0 and rw>0 and cm>=0: dfs(rw-1, cm, flag, mp)
    try: 
        c = mp[rw][cm+1]
        b = flag[rw][cm+1]
    except: c = "#"
    if c == "." and b == 0: dfs(rw, cm+1, flag, mp)
    try: 
        c = mp[rw+1][cm]
        b = flag[rw+1][cm]
    except: c = "#"
    if c == "." and b == 0: dfs(rw+1, cm, flag, mp)
    return flag


    


    
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque

while True:
    w, h = map(int, input().split())
    if w == 0 and h == 0:
        break
    else:
        m = []
        d = deque()
        for i in range(h):
            r = input()
            m.append(list(r))
            s = r.find('@')
            if s != -1:
                d.append((s, i))
        while len(d):
            rw, rh = d.popleft()
            m[rh][rw] = 'Y'
            if 0 < rw and m[rh][rw-1] == '.':
                d.append((rw-1, rh))
                m[rh][rw-1] = 'Y'
            if rw < w-1 and m[rh][rw+1] == '.':
                d.append((rw+1, rh))
                m[rh][rw+1] = 'Y'
            if 0 < rh and m[rh-1][rw] == '.':
                d.append((rw, rh-1))
                m[rh-1][rw] = 'Y'
            if rh < h-1 and m[rh+1][rw] == '.':
                d.append((rw, rh+1))
                m[rh+1][rw] = 'Y'
        a = 0
        for i in m:
            a += i.count('Y')
        print(a)

Submission status: Accepted

Solution code:
dxy = [(1, 0), (0, 1), (-1, 0), (0, -1)]
def rec(maze, visited, locat):
  # ４方向全て試す
  for i in dxy:
    n_locat = (locat[0] + i[0], locat[1] + i[1])
    if 0 <= n_locat[0] < len(maze) and 0 <= n_locat[1] < len(maze[0]):
      if maze[n_locat[0]][n_locat[1]] == '.':
        if visited[n_locat[0]][n_locat[1]] == False:
          global count 
          count += 1
          visited[n_locat[0]][n_locat[1]] = True
          rec(maze, visited, n_locat)
  return count
while(True):
  w, h = map(int, input().split())
  if w == 0 and h == 0:
    break
  maze = [[]for i in range(h)]
  visited = [[False for i in range(w)] for j in range(h)]
  for i in range(h):
    mazel = list(input())
    maze[i] = mazel
  count = 1 # @のいちを予めカウントしておく
  for i in range(h):
    for j in range(w):
      if maze[i][j] == '@':
        s = [i, j]
        break
    else:
      continue
    break
  print(rec(maze, visited, s))

Submission status: Accepted

Solution code:
adjR = [-1, 0, 0, 1]
adjC = [0, 1, -1, 0]

def isValid(row, col, ROWS, COLS):
    return row >= 0 and row < ROWS and col >= 0 and col < COLS

def floodfill(board, row, col, ROWS, COLS):
    global adjR
    global adjC

    if not isValid(row, col, ROWS, COLS):
        return 0
    if board[row][col] == '#':
        return 0

    board[row][col] = '#'
    total = 1
    for x in range(4):
        rr = row + adjR[x]
        cc = col + adjC[x]
        total += floodfill(board, rr, cc, ROWS, COLS)
    return total
    

if __name__ == '__main__':
    while True:
        COLS, ROWS = list(map(int, input().split()))
        if ROWS == 0 and COLS == 0:
            break

        board = []
        for i in range(ROWS):
            line = input()
            board.append([ c for c in line ])
            if '@' in line:
                row = i
                col = line.find('@')
        
        print(  floodfill(board, row, col, ROWS, COLS)  )

Submission status: Accepted

Solution code:
while True:
    W, H = map(int, input().split())
    room = []
    for i in range(H):
        room.append(input())
    
    for i in range(H):
        for j in range(W):
            if room[i][j] == '@':
                (sx, sy) = (j, i)
            
    dx = (-1, 0, 1, 0)
    dy = (0, -1, 0, 1)
    visited = [[False] * W for i in range(H)]

    def rec(x, y):
        visited[y][x] = True
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if 0 <= nx < W and 0 <= ny < H and room[ny][nx] == '.':
                if not visited[ny][nx]:
                    rec(nx, ny)

    if W == 0 or H == 0:
        break
    rec(sx, sy)
    ans = 0
    for a in visited:
        for b in a:
            if b:
                ans += 1
    print(ans)

Submission status: Accepted

Solution code:
h=0
w=0

while 1:
    w,h=map(int,input().split())
    if h==0 and w==0:
        break
    grid=[]
    sx=-1
    sy=-1
    ans=1
    used=[[0]*w for i in range(h)]
    def valid(i,j):
        return i>=0 and j>=0 and i<h and j<w and grid[i][j]=='.' and not used[i][j]
    for i in range(h):
        row=input()
        grid.append(row)
        for j in range(w):
            if row[j]=='@':
                sx=i
                sy=j
    stk=[(sx,sy)]
    while stk:
        x=stk[-1][0]
        y=stk[-1][1]
        stk.pop()
        for d in [(1,0),(0,1),(-1,0),(0,-1)]:
            xx=x+d[0]
            yy=y+d[1]
            if valid(xx,yy):
                stk.append((xx,yy))
                used[xx][yy]=1
                ans+=1
    print(ans)

Submission status: Accepted

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


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


    for i in range(h):
        for j in range(w):
            if m[i][j] == '@':
                rec(i, j)
                break
        else:
            continue
        break
    print(answer)

Submission status: Accepted

Solution code:
def count_area(h,w):
	count = 0
	if (h>0) and (s[h-1][w]== "."):
		s[h-1][w] = "#"
		count += count_area(h-1,w)
	if (h<H-1) and (s[h+1][w]== "."):
		s[h+1][w] = "#"
		count += count_area(h+1,w)
	if (w>0) and (s[h][w-1]== "."):
		s[h][w-1] = "#"
		count += count_area(h,w-1)
	if (w<W-1) and (s[h][w+1]== "."):
		s[h][w+1] = "#"
		count += count_area(h,w+1)
	return count+1

while(True):
	W, H = map(int, input().split())
	if H==0&W==0:break

	s = [list(input()) for i in range(H)]
	
	for h in range(H):
		for w in range(W):
			if s[h][w] == "@":
				s[h][w] = "#"
				print(count_area(h,w))
				break