Problem:


爆弾の連鎖

縦 8、横 8 のマスからなる図1 のような平面があります。その平面上に、いくつかの爆弾が置かれています。図2 にその例を示します（● = 爆弾）。

	

               
□□□□□□□□

	       
□□□□□□□□

	       
□□□□□□□□

	       
□□□□□□□□

	       
□□□□□□□□

	       
□□□□□□□□

	       
□□□□□□□□

	       
□□□□□□□□

	

       	       
□□□●□□●□

	       
□□□□□●□□

	       
●□□□●□□●

	       
□□●□□□●□

	       
□●□□□□□□

	       
□□□□●□□□

	       
●□●□□□●□

	       
□●□●□□●□

	       
	

図1図2

爆弾が爆発すると、その爆弾の上下左右 3 マスに爆風の影響が及び、それらのマスに置かれている爆弾も連鎖的に爆発します。たとえば、図 3 に示す爆弾が爆発すると図 4 の■のマスに爆風の影響が及びます。

	

               
□□□□□□□□

	       
□□□□□□□□

	       
□□□□□□□□

	       
□□□□□□□□

	       
□□□□□□□□

	       
□□□●□□□□

	       
□□□□□□□□

	       
□□□□□□□□

	

  
□□□□□□□□

	       
□□□□□□□□

	       
□□□■□□□□

	       
□□□■□□□□

	       
□□□■□□□□

	       
■■■●■■■□

	       
□□□■□□□□

	       
□□□■□□□□

	       
	

図3図4

爆弾が置かれている状態と最初に爆発する爆弾の位置を読み込んで、最終的な平面の状態を出力するプログラムを作成してください。

Input

入力は以下の形式で与えられます。

n
（空行）
データセット 1
（空行）
データセット 2
..
..
データセット n

１行目にデータセットの数 n (n ≤ 20) が与えられます。続いて n 個のデータセットが与えられます。各データセットの直前に１つの空行が与えられます。各データセットは以下の形式で与えられます。

g1,1g2,1...g8,1
g1,2g2,2...g8,2
:
g1,8g2,8...g8,8
X
Y

最初の８行に、平面を表す８つの文字列が与えられます。各文字列は８文字からなる数列で、爆弾が置かれているマスを 1、置かれていないマスを 0 で表します。
続く２行で、最初に爆発する爆弾の X 座標と Y 座標が与えられます。左上、左下、右上、右下の座標が、それぞれ、(1, 1)、(1, 8)、(8, 1)、(8, 8) です。例えば、図 4 に示す爆弾が最初に爆発するとき、与えられる座標は (4, 6) です。

Output

各データセットについて以下のように出力して下さい。

爆発しないで残った爆弾のあるマスを 1、爆弾のないマスを 0 で表現することとします。平面の一行を数字 8 個からなる一行とし 8 行の文字列で最終的な平面の状態を出力してください。各データセットの先頭は、サンプル出力のように Data x: から出力しなければなりません。ここで、x はデータセットの番号です。

Sample Input

2

00010010
00000100
10001001
00100010
01000000
00001000
10100010
01010010
2
5

00010010
00000100
10001001
00100010
01000000
00001000
10100010
01010010
2
5

Output for the Sample Input

Data 1:
00000000
00000100
10001001
00100000
00000000
00001000
10100000
00000000
Data 2:
00000000
00000100
10001001
00100000
00000000
00001000
10100000
00000000



Sample input:
2

00010010
00000100
10001001
00100010
01000000
00001000
10100010
01010010
2
5

00010010
00000100
10001001
00100010
01000000
00001000
10100010
01010010
2
5


Sample output:
Data 1:
00000000
00000100
10001001
00100000
00000000
00001000
10100000
00000000
Data 2:
00000000
00000100
10001001
00100000
00000000
00001000
10100000
00000000

Submission status: Wrong Answer

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

import sys
import os
import itertools

T = int(input())
for t in range(T):
    input()

    map = []
    for i in range(8):
        s = input().strip()
        map.append(list(s))

    X = int(input())
    Y = int(input())
    X -= 1
    Y -= 1

    def exist_bomb(x, y):
        if 0 <= x < 8 and 0 <= y < 8 and map[y][x] == '1':
            return True
        else:
            return False

    Q = []
    Q.append((X, Y))

    while Q:
        x, y = Q.pop(0)
        
        for i in range(1, 4):
            if exist_bomb(x + i, y):
                Q.append((x + i, y))
                map[y][x+i] = '0'

            if exist_bomb(x - i, y):
                Q.append((x - i, y))
                map[y][x-i] = '0'

            if exist_bomb(x, y + i):
                Q.append((x, y + i))
                map[y+i][x] = '0'

            if exist_bomb(x, y - i):
                Q.append((x, y - i))
                map[y-i][x] = '0'

    # result
    print("Data {}:".format(t+1))
    for row in map:
        print(''.join(row))

Submission status: Wrong Answer

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

import sys
import os
import itertools

T = int(input())
for t in range(T):
    input()

    map = []
    for i in range(8):
        s = input().strip()
        map.append(list(s))

    X = int(input())
    Y = int(input())
    X -= 1
    Y -= 1

    def exist_bomb(x, y):
        if 0 <= x < 8 and 0 <= y < 8 and map[y][x] == '1':
            return True
        else:
            return False

    Q = []
    Q.append((X, Y))

    while Q:
        x, y = Q.pop(0)

        for i in range(1, 4):
            if exist_bomb(x + i, y):
                Q.append((x + i, y))
                map[y][x+i] = '0'

            if exist_bomb(x - i, y):
                Q.append((x - i, y))
                map[y][x-i] = '0'

            if exist_bomb(x, y + i):
                Q.append((x, y + i))
                map[y+i][x] = '0'

            if exist_bomb(x, y - i):
                Q.append((x, y - i))
                map[y-i][x] = '0'

    # result
    print("Data {}:".format(t+1))
    for row in map:
        print(''.join(row))

Submission status: Wrong Answer

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

import sys
import os
import itertools

T = int(input())
for t in range(T):
    input()

    map = []
    for i in range(8):
        s = input().strip()
        map.append(list(s))

    X = int(input())
    Y = int(input())
    X -= 1
    Y -= 1

    def exist_bomb(x, y):
        if 0 <= x < 8 and 0 <= y < 8 and map[y][x] == '1':
            return True
        else:
            return False

    Q = []
    Q.append((X, Y))

    while Q:
        x, y = Q.pop(0)

        for i in range(1, 4):
            if exist_bomb(x + i, y):
                Q.append((x + i, y))
                map[y][x+i] = '0'

            if exist_bomb(x - i, y):
                Q.append((x - i, y))
                map[y][x-i] = '0'

            if exist_bomb(x, y + i):
                Q.append((x, y + i))
                map[y+i][x] = '0'

            if exist_bomb(x, y - i):
                Q.append((x, y - i))
                map[y-i][x] = '0'

    # result
    if t != 0:
        print()
    print("Data {}:".format(t+1))
    for i, row in enumerate(map):
        print(''.join(row), end='')
        if i != 7:
            print()

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0071
"""
import sys


def check_bombs(map, pos, dir, range=3):
    """
    ????¢¨????±???????????????\??????????????????????????§???????????????
    (?????°????????????????¢¨????±??????´?????§????????????????????????????????????????????§????????????????????????)
    :param map: ?????¨?????¶???
    :param pos: ???????????????????????????
    :param dir: ?????§????????????????¢¨????????? (up, down, left, right)
    :param range: ????¢¨????±??????????
    :return: ???????????????????????????????????? or None
    """
    if dir == 'up':
        x, y = pos
        while range > 0 and y > 0:
            if map[y-1][x] == '1':
                return (x, y-1)
            else:
                y -= 1
                range -= 1
    elif dir == 'down':
        x, y = pos
        while range > 0 and y < len(map)-1:
            if map[y+1][x] == '1':
                return (x, y+1)
            else:
                y += 1
                range -= 1
    elif dir == 'left':
        x, y = pos
        while range > 0 and x > 0:
            if map[y][x-1] == '1':
                return (x-1, y)
            else:
                x -= 1
                range -= 1
    elif dir == 'right':
        x, y = pos
        while range > 0 and x < len(map[0])-1:
            if map[y][x+1] == '1':
                return (x+1, y)
            else:
                x += 1
                range -= 1
    else:
        return None


def chain_bombs(map, init_pos):
    """
    ???????????£?????????????????¶???????¨??????????
    :param map: ???????????????????????¶???
    :param init_pos: (0, 0)?????????????????????????????????????????????????????§?¨?
    :return: ??????????????????????????¶???
    """
    lmap = map[:]               #  ??????????????¶????¨??????¨
    detonated = [init_pos]      #  ??±?????????????????????????????????(????????????)
    while detonated:
        x, y = detonated.pop()
        lmap[y][x] = '0'
        res = check_bombs(lmap, (x, y), 'up')
        if res:
            detonated.append(res)
        res = check_bombs(lmap, (x, y), 'down')
        if res:
            detonated.append(res)
        res = check_bombs(lmap, (x, y), 'left')
        if res:
            detonated.append(res)
        res = check_bombs(lmap, (x, y), 'right')
        if res:
            detonated.append(res)
    return lmap


def main(args):
    data_set = int(input())
    maps = []
    init_pos = []
    for i in range(data_set):
        _ = input()
        maps.append([list(input().strip()) for _ in range(8)])
        init_pos.append([int(input())-1, int(input())-1]) #  ??§?¨????0???????????????????????????

    count = 1
    for map, pos in zip(maps, init_pos):
        result = chain_bombs(map, pos)
        print('Data {}:'.format(count))
        for row in result:
            print(''.join(row))


if __name__ == '__main__':
    main(sys.argv[1:])

Submission status: Wrong Answer

Solution code:
# Aizu Problem 0071: Bombs Chain
#
import sys, math, os

# read input:
PYDEV = os.environ.get('PYDEV')
if PYDEV=="True":
    sys.stdin = open("sample-input.txt", "rt")


def bombs_chain(grid, row, col):
    offsets = [[1, 0], [-1, 0], [0, 1], [0, -1]]
    queue = [(row, col)]
    while len(queue) > 0:
        row0, col0 = queue.pop(0)
        for row_off, col_off in offsets:
            for k in range(1, 4):
                row = row0 + row_off * k
                col = col0 + col_off * k
                if 0 <= row < 8 and 0 <= col < 8 and grid[row][col] == 1:
                    grid[row][col] = 0
                    queue.append((row, col))
    return grid

    
N = int(input())
for case in range(N):
    input()
    grid = [[int(_) for _ in input().strip()] for __ in range(8)]
    col = int(input()) - 1
    row = int(input()) - 1
    grid = bombs_chain(grid, row, col)
    print("Data %d:" % (case + 1))
    for row in grid:
        print(''.join([str(r) for r in row]))

Submission status: Wrong Answer

Solution code:
def e(x,y):
 A[y][x]='0'
 for dx,dy in[[-3,0],[-2,0],[-1,0],[1,0],[2,0],[3,0],[0,-3],[0,-2],[0,-1],[0,1],[0,2],[0,3]]:
  if 0<=x+dx<8 and 0<=y+dy<8 and A[y+dy][x+dx]=='1':e(x+dx,y+dy)

for i in range(int(input())):
 print(f'Data {i+1}')
 input()
 A=[list(input())for _ in[0]*8]
 e(int(input())-1,int(input())-1)
 for r in A:print(*r,sep='')

Submission status: Wrong Answer

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

import sys


def board_to_string(board):
    return "\n".join(["".join([str(i) for i in row]) for row in board])


def get_answer(board, positions):
    x, y = positions.pop(0)
    board[y][x] = 0
    explode_range = []

    for i in [j for j in xrange(-3, 4) if j]:
        if (0 <= (x + i) <= 7):
            explode_range.append((x + i, y))
        if (0 <= (y + i) <= 7):
            explode_range.append((x, y + i))

    for explode_pos in explode_range:
        x, y = explode_pos
        if board[y][x] == 1:
            board[y][x] = 0
            positions.append((x, y))
    if positions:
        return get_answer(board, positions)
    else:
        return board


def main():
    s = sys.stdin.read()
    params = [param.rstrip() for param in s.split("\n\n")][1:]
    
    for i, param in enumerate(params):
        print "Data %d:" % (i + 1)

        lines = param.split("\n")
        board = [map(int, line) for line in lines[:-2]]
        x, y = map(int, lines[-2:])
        x -= 1
        y -= 1
        positions = []
        positions.append((x, y))

        print positions
        ans_board = get_answer(board, positions)
        print board_to_string(ans_board)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
x=[0,0,0,0,0,0,1,2,3,-1,-2,-3]
y=[1,2,3,-1,-2,-3,0,0,0,0,0,0]

def dfs(ty,tx):
    if 0<=ty<8 and 0<=tx<8 and L[ty][tx]==1:
        L[ty][tx]=0
        for i,j in zip(x,y):
            dx,dy=tx+i,ty+j
            if 0<=dx<=7 and 0<=dy<=7:
                dfs(dy,dx)
    return

n=input()
for i in range(n):
    L=[map(int,raw_input()) for j in range(8)]
    ax,ay=input(),input()
    dfs(ay-1,ax-1)
    print "Data %d:"%(i+1)
    for j in range(8):
        print "".join(map(str,L[j]))

Submission status: Wrong Answer

Solution code:
dx = [-3, -2, -1, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3]
dy = [0, 0, 0, -1, -2, -3, 0, 1, 2, 3, 0, 0, 0]

T = input()
for t in xrange(1, T + 1):
    field = []
    raw_input()
    for i in xrange(8):
        field.append(map(int, raw_input()))
    x, y = input() - 1, input() - 1
    for k in xrange(len(dx)):
        ny = y + dy[k]
        nx = x + dx[k]
        if nx < 0 or ny < 0 or nx >= 8 or ny >= 8:
            continue
        field[ny][nx] = 0
    print "Data %d:" % t
    for i in xrange(8):
        print ''.join(map(str, field[i]))

Submission status: Accepted

Solution code:
from itertools import chain, repeat

def solve(a, x, y):
    a[y][x] = 0
    for dx, dy in chain(zip(range(-3, 4), repeat(0)), zip(repeat(0), range(-3, 4))):
        if a[y+dy][x+dx]:
            solve(a, x+dx, y+dy)

for i in range(1, int(input())+1):
    input()
    empty = [[0]*14]*3
    a = empty + [[0,0,0]+list(map(int, input()))+[0,0,0] for _ in [0]*8] + empty
    x, y = int(input()), int(input())
    solve(a, x+2, y+2)

    print("Data {}:".format(i))
    for l in a[3:-3]:
        print("".join(map(str, l[3:-3])))

Submission status: Accepted

Solution code:
def bom(X,Y,point):
    point[Y][X]="0"
    for x,y in [[-3,0],[-2,0],[-1,0],[1,0],[2,0],[3,0],[0,-3],[0,-2],[0,-1],[0,1],[0,2],[0,3]]:
        if 0<=X+x<8 and 0<=Y+y<8 and point[Y+y][X+x]=="1":bom(X+x,Y+y,point)
    return point

for i in range(int(input())):
    input()
    point=[list(input()) for _ in [0]*8]
    X=int(input())-1
    Y=int(input())-1
    print("Data "+str(i+1)+":")
    answer=bom(X,Y,point)
    answer_box=[]
    for i in range(8):
        p=""
        for j in range(8):
            p +=answer[i][j]
            if j==7:
                answer_box.append(p)
    for k in range(8):
        print(answer_box[k])

Submission status: Accepted

Solution code:
n = int(input())

for i in range(n):
	input()
	board = [list(input()) for i in range(8)]
	sx = int(input()) - 1
	sy = int(input()) - 1

	board[sy][sx] == 2
	bomb = []
	n_bomb = [[sy, sx]]
	points = []
	for j in range(len(board)):
		while '1' in board[j]:
			px = board[j].index('1')
			py = j
			points.append([py, px])
			board[j][px] = '2'
	
	while len(n_bomb) != 0:
		bomb += n_bomb
		n_bomb = []
		for b in bomb:
			for p in points:
				if (p[0] == b[0] and b[1]-3 <= p[1] <= b[1]+3) or (p[1] == b[1] and b[0]-3 <= p[0] <= b[0]+3):
					points.remove(p)
					n_bomb.append(p)
	
	ans = [['0'] * 8 for j in range(8)]
	for p in points:
		ans[p[0]][p[1]] = '1'

	print("Data %s:" % str(i+1))
	for p in ans:
		print("".join(p))

Submission status: Accepted

Solution code:
def solve(d,x,y):
    d[y][x] = 0
    bomb = [ [-3,0],[-2,0],[-1,0],[1,0],[2,0],[3,0],[0,-3],[0,-2],[0,-1],[0,1],[0,2],[0,3] ]
    for dx,dy in bomb:
        if 0 <= dx+x <= 7 and 0 <= dy+y <= 7 and d[dy+y][dx+x] :
                solve(d,dx+x,dy+y)
    return d


n = input()
for i in xrange(n):
    raw_input()
    data = []
    for j in xrange(8):
        data.append( map(int,raw_input()) )
    fx = input()
    fy = input()
    ans = solve(data,fx-1,fy-1)
    print "Data %d:" % (i+1)
    for e in ans:
        print "".join(map(str,e))

Submission status: Accepted

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

MAX_Y = 8
MAX_X = 8

def main():
    # 入力
    N = int(raw_input())

    for i , j in enumerate(range(N)):
        raw_input()

        data = []
        for j in range(MAX_Y):
            input_list = map(int, raw_input())
            data.append(input_list)
        bomb_X = int(raw_input())
        bomb_Y = int(raw_input())
        
        bomb_town = explosion(data, ((bomb_X-1, bomb_Y-1),))
        print("Data " + str(i+1) + ":")
        printBomb(bomb_town)

def printBomb(bomb):
    for x in bomb:
        print(reduce(lambda x, y: x+y, (map(str, x))))

# 盤面内か判定
def isIn(x, y):
    return 0<=x<MAX_X and 0<=y<MAX_Y

# 爆弾を爆破
def explosion(data, bomb):
    for b in bomb:
        if data[b[1]][b[0]] == 1:
            new_bomb = bom(data, b)
            burned_data = burned(data, b)
            data = explosion(burned_data, new_bomb)

    return data

# 燃やす
def burned(data, b):
    data[b[1]][b[0]] = 0
    return data

# 燃焼範囲をチェック
def bom(data, b):
    bom_area =  [(-3, 0), (-2, 0), (-1, 0), (1, 0), (2, 0), (3, 0),
                (0, -3), (0, -2), (0, -1), (0, 1), (0, 2), (0, 3)]
    new_bomb = []
    for x in bom_area:
        bomb = tuple([sum(x) for x in zip(x,b)])
        if isIn(*bomb):
            new_bomb.append(bomb)

    return new_bomb

if __name__=='__main__':
    main()

Submission status: Accepted

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

MAX_Y = 8
MAX_X = 8

def main():
    # 入力
    N = int(raw_input())

    for i , j in enumerate(range(N)):
        raw_input()

        data = []
        for j in range(MAX_Y):
            input_list = map(int, raw_input())
            data.append(input_list)
        bomb_X = int(raw_input())
        bomb_Y = int(raw_input())

        bomb_town = explosion(data, ((bomb_X-1, bomb_Y-1),))
        print("Data " + str(i+1) + ":")
        printBomb(bomb_town)

def printBomb(bomb):
    for x in bomb:
        print(reduce(lambda x, y: x+y, (map(str, x))))

# 盤面内か判定
def isIn(x, y):
    return 0<=x<MAX_X and 0<=y<MAX_Y

# 爆弾を爆破
def explosion(data, bomb):
    for b in bomb:
        if data[b[1]][b[0]] == 1:
            new_bomb = bom(data, b)
            burned_data = burned(data, b)
            data = explosion(burned_data, new_bomb)

    return data

# 燃やす
def burned(data, b):
    data[b[1]][b[0]] = 0
    return data

# 燃焼範囲をチェック
def bom(data, b):
    bomb_area =  [(-3, 0), (-2, 0), (-1, 0), (1, 0), (2, 0), (3, 0),
                (0, -3), (0, -2), (0, -1), (0, 1), (0, 2), (0, 3)]
    new_bomb = []
    for x in bomb_area:
        buf = tuple([sum(x) for x in zip(x,b)])
        if isIn(*buf):
            new_bomb.append(buf)

    return new_bomb

if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
import sys
f = sys.stdin

def bomb(board, x, y):
    if x < 0 or y < 0 or len(board) <= x or len(board) <= y:
        return
    if board[y][x] == '0':
        return
    board[y] = board[y][:x] + '0' + board[y][x + 1:]
    for dx, dy in [[0, -3],[0, -2],[0, -1],[3, 0],[2, 0],[1, 0],[0, 3],[0, 2],[0, 1],[-3, 0],[-2, 0],[-1, 0]]:
        bomb(board, x + dx, y + dy)
    

n = int(f.readline())
for i in range(n):
    f.readline() #空行
    board = [f.readline().strip() for _ in range(8)]
    x, y = map(int, [f.readline() for _ in range(2)])
    
    bomb(board, x - 1, y - 1)
    
    print('Data {}:'.format(i + 1))
    for line in board:
        print(line)

Submission status: Accepted

Solution code:
def solve(data,p):
    L=[]
    if data[p[1]-1][p[0]-1]=="1":
        data[p[1]-1]=data[p[1]-1][:p[0]-1]+"0"+data[p[1]-1][p[0]:]
        L+=p
    else:
        return []
    bakuhu=[(p[0]-3,p[1]),(p[0]-2,p[1]),(p[0]-1,p[1]),(p[0]+1,p[1]),(p[0]+2,p[1]),(p[0]+3,p[1]),(p[0],p[1]-3),(p[0],p[1]-2),(p[0],p[1]-1),(p[0],p[1]+1),(p[0],p[1]+2),(p[0],p[1]+3)]
    for i in range(len(bakuhu)):
        if bakuhu[i][0]>0 and bakuhu[i][1] >0 and bakuhu[i][0] <9 and bakuhu[i][1] <9:
            L.extend(solve(data,bakuhu[i]))
    return L
    
while True:
    try:
        ndata=input()
        for i in range(ndata):
            raw_input()
            data=[]
            for j in range(8):
                data.append(raw_input())
            x=input()
            y=input()
            p=(x,y)
            L=solve(data,p)
            while len(L)!=0:
                x=L.pop(0)
                y=L.pop(0)
                data[y-1]=data[y-1][:x-1]+'0'+data[y-1][x:]
            print "Data "+str(i+1)+':'
            for i in range(len(data)):
                print data[i]
    except:
        break

Submission status: Accepted

Solution code:
def chain(y, x):
	bomb[y][x] = "0"
	if bomb[y + 1][x] == "1" : chain(y + 1, x)
	if bomb[y + 2][x] == "1" : chain(y + 2, x)
	if bomb[y + 3][x] == "1" : chain(y + 3, x)
	if bomb[y - 1][x] == "1" : chain(y - 1, x)
	if bomb[y - 2][x] == "1" : chain(y - 2, x)
	if bomb[y - 3][x] == "1" : chain(y - 3, x)
	if bomb[y][x + 1] == "1" : chain(y, x + 1)
	if bomb[y][x + 2] == "1" : chain(y, x + 2)
	if bomb[y][x + 3] == "1" : chain(y, x + 3)
	if bomb[y][x - 1] == "1" : chain(y, x - 1)
	if bomb[y][x - 2] == "1" : chain(y, x - 2)
	if bomb[y][x - 3] == "1" : chain(y, x - 3)
	return

n = input()
for d in range(0, n):
	raw_input()
	bomb = []
	for _ in range(0, 3) : bomb.append(list("00000000000000"))
	for _ in range(0, 8) : bomb.append(list("000" + raw_input() + "000"))
	for _ in range(0, 3) : bomb.append(list("00000000000000"))
	
	x = input() + 2
	y = input() + 2
	
	chain(y, x)
	
	print "Data {}:".format(d + 1)
	for var in bomb[3:11]:
		print "".join(var[3:11])

Submission status: Accepted

Solution code:
n = int(input())
def f(l,m):
    if m == []:
      return l
    else:
      m2 = []
      for s in m:
          y,x = s[0],s[1]
          l[y][x] = '0'
          for i in range(y-3,y+4):
              if 0<=i<=7 and l[i][x] == '1':
                  m2.append((i,x))
          for i in range(x-3,x+4):
              if 0<=i<=7 and l[y][i] == '1':
                  m2.append((y,i))
      return f(l,m2)
c = 0
while n > 0:
    c += 1
    input()
    l = []
    for i in range(8):
      l.append([j for j in input()])
    x = int(input())-1
    y = int(input())-1
    a = f(l,[(y,x)])
    print('Data ' + str(c) + ':')
    for i in a:
      b = ''
      for j in i:
        b += j
      print(b)
    n -= 1

Submission status: Accepted

Solution code:
def bomb(f,x,y):
    rf=f[:][:]
    rf[y][x]=0
    for i in [-3,-2,-1,1,2,3]:
        if 0<=x+i<=7:
            if rf[y][x+i]==1:
                rf=bomb(rf,x+i,y)
        if 0<=y+i<=7:
            if rf[y+i][x]==1:
                rf=bomb(rf,x,y+i)
    return rf

n=int(raw_input())
for data in range(1,n+1):
    raw_input()
    f=[]
    for i in range(8):
        f.append([int(x) for x in raw_input()])
    x=int(raw_input())-1
    y=int(raw_input())-1
       # map(int,raw_input().split())
    f=bomb(f,x,y)
    print "Data %d:"%(data)
    for i in range(8):
        print ''.join(map(str, f[i]))

Submission status: Accepted

Solution code:
d=[[-3,0],[-2,0],[-1,0],[1,0],[2,0],[3,0],[0,-3],[0,-2],[0,-1],[0,1],[0,2],[0,3]]
def f(x,y,a):
    a[y][x]='0'
    for dx,dy in d:
        if 0<=x+dx<8 and 0<=y+dy<8 and a[y+dy][x+dx]=='1':f(x+dx,y+dy,a)
    return a

for i in range(int(input())):
    print('Data %d:'%(i+1))
    input()
    a=[list(input()) for _ in [0]*8]
    for x in f(int(input())-1,int(input())-1,a):print(''.join(x))

Submission status: Accepted

Solution code:
def f(x,y,a):
    a[y][x]='0'
    for dx,dy in [[-3,0],[-2,0],[-1,0],[1,0],[2,0],[3,0],[0,-3],[0,-2],[0,-1],[0,1],[0,2],[0,3]]:
        if 0<=x+dx<8 and 0<=y+dy<8 and a[y+dy][x+dx]=='1':f(x+dx,y+dy,a)
    return a

for i in range(int(input())):
    print('Data %d:'%(i+1))
    input()
    a=[list(input()) for _ in [0]*8]
    [print(*x,sep='')for x in f(int(input())-1,int(input())-1,a)]

Submission status: Accepted

Solution code:
def f(a,x,y):
    a[y][x]='0'
    for dx,dy in [[-3,0],[-2,0],[-1,0],[1,0],[2,0],[3,0],[0,-3],[0,-2],[0,-1],[0,1],[0,2],[0,3]]:
        if 0<=x+dx<8 and 0<=y+dy<8 and a[y+dy][x+dx]=='1':f(a,x+dx,y+dy)
    return a

for i in range(int(input())):
    print('Data %d:'%(i+1));input()
    [print(*x,sep='')for x in f([list(input()) for _ in [0]*8],int(input())-1,int(input())-1)]

Submission status: Accepted

Solution code:
N = 8
dx = [-3,-2,-1,1,2,3,0,0,0,0,0,0]
dy = [0,0,0,0,0,0,-3,-2,-1,1,2,3]
def dfs(y,x,S):
    S [y] [x] = '0'
    for i in range(len(dx)):
        ny = y + dy [i]
        nx = x + dx [i]
        if 0 <= ny < N and 0 <= nx < N and S [ny] [nx] == '1':
            dfs(ny,nx,S)

T = int(input())
for testCase in range(T):
    input()
    S = []
    for i in range(N):
        S.append(list(input()))
    X = int(input()) - 1
    Y = int(input()) - 1
    dfs(Y,X,S)
    print('Data {0}:'.format(testCase + 1))
    for i in range(N):
        print(''.join(S [i]))

Submission status: Accepted

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

import sys
import os
import itertools

T = int(input())
for t in range(T):
    input()

    map = []
    for i in range(8):
        s = input().strip()
        map.append(list(s))

    X = int(input())
    Y = int(input())
    X -= 1
    Y -= 1

    def exist_bomb(x, y):
        if 0 <= x < 8 and 0 <= y < 8 and map[y][x] == '1':
            return True
        else:
            return False

    Q = []
    Q.append((X, Y))
    map[Y][X] = '0'

    while Q:
        x, y = Q.pop(0)

        for i in range(1, 4):
            if exist_bomb(x + i, y):
                Q.append((x + i, y))
                map[y][x+i] = '0'

            if exist_bomb(x - i, y):
                Q.append((x - i, y))
                map[y][x-i] = '0'

            if exist_bomb(x, y + i):
                Q.append((x, y + i))
                map[y+i][x] = '0'

            if exist_bomb(x, y - i):
                Q.append((x, y - i))
                map[y-i][x] = '0'

    # result
    print("Data {}:".format(t+1))
    for i, row in enumerate(map):
        print(''.join(row))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0071
"""
import sys


def check_bombs(map, pos, dir, range=3):
    """
    ????¢¨????±???????????????\??????????????????????????§???????????????
    (?????°????????????????¢¨????±??????´?????§????????????????????????????????????????????§????????????????????????)
    :param map: ?????¨?????¶???
    :param pos: ???????????????????????????
    :param dir: ?????§????????????????¢¨????????? (up, down, left, right)
    :param range: ????¢¨????±??????????
    :return: ???????????????????????????????????? or None
    """
    if dir == 'up':
        x, y = pos
        while range > 0 and y > 0:
            if map[y-1][x] == '1':
                return (x, y-1)
            else:
                y -= 1
                range -= 1
    elif dir == 'down':
        x, y = pos
        while range > 0 and y < len(map)-1:
            if map[y+1][x] == '1':
                return (x, y+1)
            else:
                y += 1
                range -= 1
    elif dir == 'left':
        x, y = pos
        while range > 0 and x > 0:
            if map[y][x-1] == '1':
                return (x-1, y)
            else:
                x -= 1
                range -= 1
    elif dir == 'right':
        x, y = pos
        while range > 0 and x < len(map[0])-1:
            if map[y][x+1] == '1':
                return (x+1, y)
            else:
                x += 1
                range -= 1
    else:
        return None


def chain_bombs(map, init_pos):
    """
    ???????????£?????????????????¶???????¨??????????
    :param map: ???????????????????????¶???
    :param init_pos: (0, 0)?????????????????????????????????????????????????????§?¨?
    :return: ??????????????????????????¶???
    """
    lmap = map[:]               #  ??????????????¶????¨??????¨
    detonated = [init_pos]      #  ??±?????????????????????????????????(????????????)
    while detonated:
        x, y = detonated.pop()
        lmap[y][x] = '0'
        res = check_bombs(lmap, (x, y), 'up')
        if res:
            detonated.append(res)
        res = check_bombs(lmap, (x, y), 'down')
        if res:
            detonated.append(res)
        res = check_bombs(lmap, (x, y), 'left')
        if res:
            detonated.append(res)
        res = check_bombs(lmap, (x, y), 'right')
        if res:
            detonated.append(res)
    return lmap


def main(args):
    data_set = int(input())
    maps = []
    init_pos = []
    for i in range(data_set):
        _ = input()
        maps.append([list(input().strip()) for _ in range(8)])
        init_pos.append([int(input())-1, int(input())-1]) #  ??§?¨????0???????????????????????????

    count = 1
    for map, pos in zip(maps, init_pos):
        result = chain_bombs(map, pos)
        print('Data {}:'.format(count))
        for row in result:
            print(''.join(row))
        count += 1


if __name__ == '__main__':
    main(sys.argv[1:])

Submission status: Accepted

Solution code:
def print_table(t):
    for c in t:
        for r in c:
            print("{0:d}".format(r),end="")
        print("")

def play(t,x,y):
    q = [[x,y]]
    while True:
        p = q.pop(0)

        x = p[0]
        y = p[1]

        t[y][x] = 0
        for i in range(1,4):
            if x+i < 8:
                if t[y][x+i] == 1:
                    q.append([x+i,y])
                    t[y][x+i] = 0
            if x-i >= 0:
                if t[y][x-i] == 1:
                    q.append([x-i,y])
                    t[y][x-i] = 0
            if y+i < 8:
                if t[y+i][x] == 1:
                    q.append([x,y+i])
                    t[y+i][x] = 0
            if y-i >= 0:
                if t[y-i][x] == 1:
                    q.append([x,y-i])
                    t[y-i][x] = 0

        if q == []:
            break
    return t
        
n = int(input())

for i in range(1,n+1):
    input() # ?????????skip

    t = [[int(i) for i in list(input())]]
    for j in range(0,7):
        t.append([int(i) for i in list(input())])
    x = int(input())
    y = int(input())

    tt = play(t,x-1,y-1)
    
    print('Data {0:d}:'.format(i))
    print_table(tt)

Submission status: Accepted

Solution code:
def get_input():
    while True:
        try:
            yield ''.join(input())
        except EOFError:
            break

def bomb(table, x, y):

    table[x][y] = False
    for i in range(1, 4):
        if x + i >= 8:
            break
        if table[x+i][y]:
            bomb(table, x+i, y)

    for i in range(1, 4):
        if x - i < 0:
            break
        if table[x-i][y]:
            bomb(table, x-i, y)

    for i in range(1, 4):
        if y + i >= 8:
            break
        if table[x][y+i]:
            bomb(table, x, y+i)

    for i in range(1, 4):
        if y - i < 0:
            break
        if table[x][y-i]:
            bomb(table, x, y-i)

    return

N = int(input())
for l in range(N):
    input()
    table = [[False for i in range(8)] for j in range(8)]
    for i in range(8):
        L = input()
        for j in range(8):
            if int(L[j]) == 1:
                table[i][j] = True

    a = int(input())
    b = int(input())
    bomb(table, b-1, a-1)

    print("Data " + str(l+1) + ":")
    for i in range(8):
        for j in range(8):
            if table[i][j]:
                print("1", end="")
            else:
                print("0", end="")
        print("")