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: Wrong Answer

Solution code:
import sys

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

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

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

Submission status: Wrong Answer

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]
                print(nx, ny)
                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: Wrong Answer

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))
    print li
    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: Wrong Answer

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

Submission status: Wrong Answer

Solution code:

def depth_first_search(x, y):
    """
    ??±???????????¢?´¢?????????
    :param x: ?????¨??°????¨?
    :param y: ?????¨??°??????
    :return: ?????°
    """

    # ????????????????????§?¢??????????
    # ??????x  ,y+1
    # ??????x+1,y
    # ??????x  ,y-1
    # ??????x-1,y
    move_list = [[0,1],[1,0],[0,-1],[-1,0]]
    for i in range(0,4,1):
        next_x = x+move_list[i][0]
        next_y = y+move_list[i][1]
        # tile_map??????????§??????§????????´??????'.'???
        if 0 <= next_x and 0 <= next_y and \
            next_x < W and next_y < H and \
            tile_map[next_y][next_x] != '#':

            # ?§?????????????????????¨??°????§??????§??????????????????"#"??????????????????
            tile_map[y][x] = '#'
            import __main__
            __main__.move_point = __main__.move_point+1
            depth_first_search(next_x, next_y)


def get_start_point(tile_map):
    """
    @????????????????????????
    :param tile_map:
    :return:
    """
    for i, y in enumerate(tile_map):
        for j, x in enumerate(y):
            if x == '@':
                return i, j



if __name__ == "__main__":
    move_point = 0
    first = True
    while (True):
        # input_1 : tile????????????
        tile_size = input('').split(' ')
        W, H = [int(x) for x in tile_size]
        if W == 0 and H == 0:
            break
        if first:
            first = False
        else:
            print('')
        tile_map=[''] * H
        for i in range(0, H, 1):
            # input_2 : tile???????????????????????????
            map_line = list(input(''))
            tile_map[i] = map_line
        start_H, start_W = get_start_point(tile_map)
        depth_first_search(start_W, start_H)
        print(move_point)

Submission status: Wrong Answer

Solution code:

def depth_first_search(x, y):
    """
    ??±???????????¢?´¢?????????
    :param x: ?????¨??°????¨?
    :param y: ?????¨??°??????
    :return: ?????°
    """

    # ????????????????????§?¢??????????
    # ??????x  ,y+1
    # ??????x+1,y
    # ??????x  ,y-1
    # ??????x-1,y
    move_list = [[0,1],[1,0],[0,-1],[-1,0]]
    for i in range(0,4,1):
        next_x = x+move_list[i][0]
        next_y = y+move_list[i][1]
        # tile_map??????????§??????§????????´??????'.'???
        if 0 <= next_x and 0 <= next_y and \
            next_x < W and next_y < H and \
            tile_map[next_y][next_x] != '#':

            # ?§?????????????????????¨??°????§??????§??????????????????"#"??????????????????
            tile_map[y][x] = '#'
            import __main__
            __main__.move_point = __main__.move_point+1
            depth_first_search(next_x, next_y)

def get_start_point(tile_map):
    """
    @????????????????????????
    :param tile_map:
    :return:
    """
    for i, y in enumerate(tile_map):
        for j, x in enumerate(y):
            if x == '@':
                return i, j



if __name__ == "__main__":
    move_point = 0
    while (True):
        # input_1 : tile????????????
        tile_size = input('').split(' ')
        W, H = [int(x) for x in tile_size]
        if W == 0 and H == 0:
            break
        tile_map=[''] * H
        for i in range(0, H, 1):
            # input_2 : tile???????????????????????????
            map_line = list(input(''))
            tile_map[i] = map_line
        start_H, start_W = get_start_point(tile_map)
        depth_first_search(start_W, start_H)
        print(move_point)

Submission status: Wrong Answer

Solution code:
def depth_first_search(x, y):
    """
    ??±???????????¢?´¢?????????
    :param x: ?????¨??°????¨?
    :param y: ?????¨??°??????
    :return: ?????°
    """

    # ????????????????????§?¢??????????
    # ??????x  ,y+1
    # ??????x+1,y
    # ??????x  ,y-1
    # ??????x-1,y
    move_list = [[0,1],[1,0],[0,-1],[-1,0]]
    for i in range(0,4,1):
        next_x = x+move_list[i][0]
        next_y = y+move_list[i][1]
        # tile_map??????????§??????§????????´??????'.'???
        if 0 <= next_x and 0 <= next_y and \
            next_x < W and next_y < H and \
            tile_map[next_y][next_x] != '#':

            # ?§?????????????????????¨??°????§??????§??????????????????"#"??????????????????
            tile_map[y][x] = '#'
            import __main__
            __main__.move_point = __main__.move_point+1
            depth_first_search(next_x, next_y)

def get_start_point(tile_map):
    """
    @????????????????????????
    :param tile_map:
    :return:
    """
    for i, y in enumerate(tile_map):
        for j, x in enumerate(y):
            if x == '@':
                return i, j

def check_testcase():
    with open('./1130-input.txt') as f:
        pre_input_testcase = f.read()
    with open('./1130-output.txt') as f:
        pre_output_testcase = f.read()
    pre_input_testcase = pre_input_testcase.splitlines()
    output_testcase = pre_output_testcase.splitlines()

    test_tile_size = [0]*len(output_testcase)
    test_tile_map = [[""]]*len(output_testcase)
    map_info_cnt = 0
    map_info_index = 0
    for v in pre_input_testcase:
        if map_info_cnt == 0:
            W, H = [int(x) for x in v.split(' ')]
            test_tile_size.append([W, H])
            map_info_cnt = H
            map_info_index = map_info_index+1
        else:
            print(map_info_index)
            test_tile_map[map_info_index]=test_tile_map[map_info_index].append(v)
            map_info_cnt = map_info_cnt -1
    import ipdb;ipdb.set_trace()

if __name__ == "__main__":
    move_point = 0
    while (True):
        # input_1 : tile????????????
        tile_size = input('').split(' ')
        W, H = [int(x) for x in tile_size]
        if W == 0 and H == 0:
            break
        tile_map=[''] * H
        for i in range(0, H, 1):
            # input_2 : tile???????????????????????????
            map_line = list(input(''))
            tile_map[i] = map_line
        start_H, start_W = get_start_point(tile_map)
        depth_first_search(start_W, start_H)
        print(move_point)

Submission status: Wrong Answer

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(h):
        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: Wrong Answer

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]); ans = 0;
    while len(s)>0:
        x,y = s.pop()
        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: Time Limit Exceeded

Solution code:
while True:
    W,H = [int(x) for x in input().split()]
    if W==0 and H==0:
        exit()
    tiles = []
    X = 0
    Y = 0
    for i in range(H):
        tiles.append(input())
        if '@' in tiles[i]:
            Y = i
            X = tiles[i].index('@')
    d = [[9999 for j in range(H*W)] for i in range(H*W)]
    for i in range(H*W):
        d[i][i] = 0
    for i in range(H):
        for j in range(W):
            if j>0:
                if tiles[i][j] in '.@' and tiles[i][j-1] in '.@':
                    d[W*i+j][W*i+j-1] = 1
            if j<W-1:
                if tiles[i][j] in '.@' and tiles[i][j+1] in '.@':
                    d[W*i+j][W*i+j+1] = 1
            if i>0:
                if tiles[i][j] in '.@' and tiles[i-1][j] in '.@':
                    d[W*i+j][W*i+j-W] = 1
            if i<H-1:
                if tiles[i][j] in '.@' and tiles[i+1][j] in '.@':
                    d[W*i+j][W*i+j+W] = 1
    for k in range(H*W):
        for i in range(H*W):
            for j in range(H*W):
                if d[i][j] > d[i][k]+d[k][j]:
                    d[i][j] = d[i][k]+d[k][j]
    cnt = 0
    for i in range(H*W):
        if d[X+Y*W][i]<9999:
            cnt += 1
    print(cnt)

Submission status: Accepted

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

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


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

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

for i in anslist:
    print(i)

Submission status: Accepted

Solution code:
from queue import Queue

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

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


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

    return calcReachableTileNumByBFSearch(room, start)


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


if __name__ == "__main__":
    main()

Submission status: Accepted

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

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

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

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

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

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

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

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
#! /usr/bin/env python
# -*- coding: utf-8 -*-

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

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

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

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

Submission status: Accepted

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

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

Submission status: Accepted

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

Submission status: Accepted

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

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

Submission status: Accepted

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

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

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:

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

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

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

Submission status: Accepted

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

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

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

Submission status: Accepted

Solution code:
vx = [1, -1, 0, 0]
vy = [0, 0, 1, -1]


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


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

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

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

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

    if W == 0:
        break

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

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

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

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import array
import itertools
import sys


UNDET_POINT = (-1, -1)


class RecursiveDepthFirstSearch(object):

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

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

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


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

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import array
import collections
import itertools


class DepthFirstSearchWithStack(object):

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

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

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


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

Submission status: Accepted

Solution code:
import sys

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

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

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

Submission status: Accepted

Solution code:
from Queue import Queue

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

Submission status: Accepted

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

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

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