Problem:


Score : 200 points

Problem Statement

You are given an H × W grid.

The squares in the grid are described by H strings, S_1,...,S_H.

The j-th character in the string S_i corresponds to the square at the i-th row from the top and j-th column from the left (1 \leq i \leq H,1 \leq j \leq W).

. stands for an empty square, and # stands for a square containing a bomb.  

Dolphin is interested in how many bomb squares are horizontally, vertically or diagonally adjacent to each empty square.

(Below, we will simply say "adjacent" for this meaning. For each square, there are at most eight adjacent squares.)

He decides to replace each . in our H strings with a digit that represents the number of bomb squares adjacent to the corresponding empty square.  

Print the strings after the process.  

Constraints

1 \leq H,W \leq 50

S_i is a string of length W consisting of # and ..

Input

Input is given from Standard Input in the following format:  

H W
S_1
:
S_H

Output

Print the H strings after the process.

The i-th line should contain a string T_i of length W, where the j-th character in T_i corresponds to the square at the i-th row from the top and j-th row from the left in the grid (1 \leq i \leq H, 1 \leq j \leq W).  

Sample Input 1

3 5
.....
.#.#.
.....

Sample Output 1

11211
1#2#1
11211

For example, let us observe the empty square at the first row from the top and first column from the left.

There is one bomb square adjacent to this empty square: the square at the second row and second column.

Thus, the . corresponding to this empty square is replaced with 1.  

Sample Input 2

3 5
#####
#####
#####

Sample Output 2

#####
#####
#####

It is possible that there is no empty square.  

Sample Input 3

6 6
#####.
#.#.##
####.#
.#..#.
#.##..
#.#...

Sample Output 3

#####3
#8#7##
####5#
4#65#2
#5##21
#4#310



Sample input:
3 5
.....
.#.#.
.....


Sample output:
11211
1#2#1
11211

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
f = []
for i in range(H):
    f.append(input())
for i in range(H):
    for j in range(W):
        if '#' == f[i][j]:
            print('#', end="")
        else:
            sum = 0
            if i - 1 >= 0:
                if j - 1 >= 0:
                    if f[i-1][j-1] == '#':
                        sum = sum + 1
                if j >= 0:
                    if f[i-1][j] == '#':
                        sum = sum + 1
                if j + 1 < W:
                    if f[i-1][j+1] == '#':
                        sum = sum + 1
            if j - 1 >= 0:
                if f[i][j-1] == '#':
                    sum = sum + 1
            if f[i][j] == '#':
                sum = sum + 1
            if j + 1 < W:
                if f[i][j+1] == '#':
                    sum = sum + 1
            if i  + 1 < H:
                if j - 1 >= 0:
                    if f[i+1][j-1] == '#':
                        sum = sum + 1
                if j >= 0:
                    if f[i+1][j] == '#':
                        sum = sum + 1
                if j + 1 < W:
                    if f[i+1][j+1] == '#':
                        sum = sum + 1
            print(sum, end="")
    print()

Submission status: Accepted

Solution code:
h,w = input().split()
h = int(h)
w = int(w)
s_list = []
for _ in range(h):
    s = input()
    s_chars =[]
    for char in s:
        s_chars.append(char)
    s_list.append(s_chars)

import numpy as np
ar = np.array(s_list)
ar = np.insert(ar,0,[["."]*w],axis=0)
ar = np.insert(ar,h+1,[["."]*w],axis=0)
ar = np.insert(ar,0,[["."]*(h+2)],axis=1)
ar = np.insert(ar,w+1,[["."]*(h+2)],axis=1)
answer_list = []
for i in range(1,h+1):
    syoukei = ""
    for j in range(1,w+1):
        if ar[i,j] == ".":
            count = 0
            for k in range(i-1,i+2):
                for l in range(j-1,j+2):
                    if ar[k,l] == "#":
                        count += 1
            syoukei += str(count)
        else:
            syoukei += "#"
    answer_list.append(syoukei)

for ans in answer_list:
    print(ans)

Submission status: Accepted

Solution code:
import sys
H,W = input().split()
H,W = int(H),int(W)
board = [["0" for w in range(W+2)] for h in range(H+2)]

for h in range(H):
    tmp = list(input())
    for w in range(W):
        board[h+1][w+1] = tmp[w]

ansboard = [["." for w in range(W+2)] for h in range(H+2)]

for h in range(H+2):
    for w in range(W+2):
        if board[h][w] == 0:
            pass
        elif board[h][w] == ".":
            counter = 0
            for j in range(3):
                for i in range(3):
                    if board[h-(j-1)][w-(i-1)] == "#":
                        counter += 1
            ansboard[h][w] = counter
        else:
            ansboard[h][w] = "#"

for h in range(H):
    for w in range(W):
        sys.stdout.write(str(ansboard[h+1][w+1]))
    sys.stdout.write("\n")

Submission status: Accepted

Solution code:
def solve():
    H, W = list(map(int, input().split(" ")))
    field = []
    for _ in range(H):
        field.append(list(input()))
    answer = [[None] * W for _ in range(H)]

    for i in range(H):
        for j in range(W):
            if field[i][j] == ".":
                cnt = 0
                for x in [-1, 0, 1]:
                    for y in [-1, 0, 1]:
                        dx = i + x
                        dy = j + y
                        if dx >= 0 and dx < H and dy >=0 and dy < W and field[dx][dy] == "#":
                            cnt += 1
                    answer[i][j] = cnt
            else:
                answer[i][j] = "#"


    for i, col in enumerate(answer):
        answer[i] = [str(x) for x in col]

    for col in answer:
        print("".join(col))
        
        
solve()

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
s = ['0'*(w+2)]

for i in range(1,h+1) :
    tmp = input().replace('.', '0')
    tmp = tmp.replace('#', '1')
    s.append('0' + tmp + '0')
s.append('0'*(w+2))

ans = [''*w for _ in range(h)]
for i in range(h) :
    for j in range(w) :
        if s[i+1][j+1] == '1' :
            ans[i] += '#'
        else :
            ans[i] += str(int(s[i][j])  +int(s[i+1][j])  +int(s[i+2][j])+
                          int(s[i][j+1])+                 int(s[i+2][j+1])+
                          int(s[i][j+2])+int(s[i+1][j+2])+int(s[i+2][j+2]))

for ss in ans :
    print(ss)

Submission status: Accepted

Solution code:
# coding: utf-8
# Here your code !
h,w=[int(x) for x in input().split()]
s=[""]*h
for i in range(h):
    s[i]=list(input())
from itertools import product
for i,j in product(range(h),range(w)):
    if s[i][j]=="#":
        continue
    ans=0
    for p,k in product([i-1,i,i+1],[j-1,j,j+1]):
        try:
            if p<0 or k<0:
                continue
            if s[p][k]=="#":
                ans+=1
        except:
            pass
    s[i][j]=str(ans)
for i in s:
    print("".join(i))

Submission status: Accepted

Solution code:
def makelist(n, m):
    return [[0 for i in range(m)] for j in range(n)]


H, W = map(int, input().split())
S = [0]*H
for i in range(H):
    S[i] = input()

ans = makelist(H, W)

def check(p):
    x, y = p
    return x >= 0 and y >= 0 and x < W and y < H

def calc(p, vol):
    return (p[0]+vol[0], p[1]+vol[1])

vols = [ (x, y) for x in range(-1, 2) for y in range(-1, 2) if x != 0 or y != 0] 

for y in range(H):
    for x in range(W):
        if S[y][x] == '#':
            ans[y][x] = '#'
            for vol in vols:
                now = calc((x, y), vol)
                if check(now):
                    if ans[now[1]][now[0]] != '#':
                        ans[now[1]][now[0]] += 1
for e in ans:
    print("".join(map(str, e)))

Submission status: Accepted

Solution code:
H, W = [int(i) for i in input().split()]
s = [input() for _ in range(H)]
dirs = [[1,0], [1,1], [0,1], [-1,1], [-1,0], [-1,-1], [0,-1], [1,-1]]

for i in range(H):
    for j in range(W):
        bomb_num = 0
        if s[i][j] == "#":
            print("#", end="")
            continue
        for d in dirs:
            dirx, diry = d
            if 0 <= j+dirx < W and 0 <= i+diry < H:
                if s[i+diry][j+dirx] == "#":
                    bomb_num += 1
        print(str(bomb_num), end="")
    print("")

Submission status: Accepted

Solution code:
# coding: utf-8

nums = [int(x) for x in input().split()]
H,W = nums[0],nums[1]

field = []
for i in range(H):
    line = [x for x in input()]
    field.append(line)


for i in range(H):
    for j in range(W):
        if field[i][j] == "#":
            continue
        else:
            # 探索処理
            cnt = 0
            for dy in [-1,0,1]:
                for dx in [-1,0,1]:
                    ny, nx = i + dy, j + dx 
                    if 0 <= ny < H and 0 <= nx < W:
                        
                        if field[ny][nx] == "#": cnt += 1

            # finally
            field[i][j] = str(cnt)


for line in field:
    print("".join(line))

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
S = [list(input()) for i in range(H)]

for i in range(H):
    S[i].append(".")
    S[i].insert(0, ".")
S.append(["."]*(W+2))
S.insert(0, ["."]*(W+2))
ans = S.copy()

for i in range(1,H+1):
    for j in range(1,W+1):
        plus = 0
        
        if S[i][j] != "#":
            adj = [S[i+1][j],S[i-1][j],S[i][j+1],S[i][j-1],S[i+1][j+1],S[i-1][j-1],S[i+1][j-1],S[i-1][j+1]]
            plus = adj.count("#")
            ans[i][j] = str(plus)
    print("".join(ans[i][1:W+1]))

Submission status: Accepted

Solution code:
h=int(raw_input().split(' ')[0])
map=[]
for x in range(h):
 map.append(raw_input())
for row in range(h):
 for col in range(len(map[row])):
  count=0
  if map[row][col]=='.':
   for x in (-1,0,1):
    for y in (-1,0,1):
     if not (x==0 and y==0) and 0<=row+y<h and 0<=col+x<len(map[row]):
      if map[row+y][col+x]=='#':
       count+=1
   map[row]=map[row][:col]+str(count)+map[row][col+1:]
for row in map:
 print row

Submission status: Accepted

Solution code:
(h, w) = input().split(" ")
(h, w) = (int(h), int(w))

s = []
for _ in range(h):
    s += [input()]

for i in range(h):
    s2 = ""
    for j in range(w):
        if s[i][j] == '#':
            s2 += "#"
            continue
        
        mines = 0
        for y in range(-1, 2):
            for x in range(-1, 2):
                ni = i+y
                nj = j+x
                if ni < 0 or ni >= h or nj < 0 or nj >= w:
                    continue
                
                if s[i+y][j+x] == '#':
                    mines += 1
        s2 += str(mines)
    print(s2)

Submission status: Accepted

Solution code:
if __name__ == '__main__':
    H, W = map(int, input().split())
    S = [list(input()) for _ in range(H)]

    d = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]
    for i in range(H):
        for j in range(W):
            if S[i][j] == "#":
                continue

            num = 0
            for x, y in d:
                if 0 <= i + x <= H - 1 and 0 <= j + y <= W - 1:
                    if S[i + x][j + y] == "#":
                        num += 1

            S[i][j] = num

    for strings in S:
        strings = map(str, strings)
        print("".join(strings))

Submission status: Accepted

Solution code:
def cnv(i0, j0):
    global h, w, s
    if s[i0][j0] == '#':
        return '#'
    else:
        cnt = 0
        for dxy in [(0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1)]:
            i = i0 + dxy[1]
            j = j0 + dxy[0]
            if 0 <= i < h and 0 <= j < w and s[i][j] == '#':
                cnt += 1
        return str(cnt)


h, w = map(int, input().split())
s = [list(input()) for _ in range(h)]

for i in range(h):
    for j in range(w):
        s[i][j] = cnv(i, j)

for si in s:
    print(''.join(si))

Submission status: Accepted

Solution code:
h, w = (int(i) for i in input().split())

inp = [[i for i in list(input())] for i in range(h)]

bombs = [[0 for _ in range(w+2)] for _ in range(h+2)]

for hh in range(h):
    for ww in range(w):
        if inp[hh][ww] =="#":
            bombs[hh][ww+2] += 1
            bombs[hh][ww] += 1
            bombs[hh][ww+1] += 1
            bombs[hh+1][ww+2] += 1
            bombs[hh+1][ww] += 1
            bombs[hh+1][ww + 1] += 1
            bombs[hh+2][ww+2] += 1
            bombs[hh+2][ww] += 1
            bombs[hh+2][ww + 1] += 1

for hh in range(h):
    for ww in range(w):
        if inp[hh][ww] == "#":
            print("#", end="")
        else:
            print(bombs[hh+1][ww+1], end="")
    print()

Submission status: Accepted

Solution code:
dxy = [-1, 0, 1]
h, w = map(int, input().split())
s = [input() for i in range(h)]

def mines(y, x):
    around = [(y + i, x + j) for i in dxy for j in dxy]
    cnt = 0
    for (i, j) in around:
        if i < 0 or h <= i or j < 0 or w <= j:
            continue
        if s[i][j] == '#':
            cnt += 1
    return cnt

for i in range(h):
    for j in range(w):
        if s[i][j] != '#':
            print(mines(i, j), end = '')
        else:
            print('#', end = '')
    print()

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
field = ["." * (w + 2)] + ["." + input() + "." for x in range(h)] + ["." * (w + 2)]

result = [["@" for x in range(w)] for x in range(h)]
#
# for i in field: print(i)
# print()

for i, row in enumerate(field[1:-1]):
    for j, cell in enumerate(row[1:-1]):
        if cell == ".":
            part = "".join(field[i + n][j:j+3] for n in range(3))
            result[i][j] = part.count("#")
        else:
            result[i][j] = "#"

for i in result: print("".join(map(str, i)))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
https://beta.atcoder.jp/contests/abc075/tasks/abc075_b

"""
import sys
from sys import stdin
input = stdin.readline


def solve(field, H, W):
    dy = [-1, 1, 0, 0, -1, -1,  1, 1]
    dx = [0, 0, -1, 1, -1,  1, -1, 1]

    for y in range(H):
        for x in range(W):
            if field[y][x] == '#':
                continue
            mine = 0
            for i in range(8):
                nx = x + dx[i]
                ny = y + dy[i]
                if (not 0 <= nx < W) or (not 0 <= ny < H):
                    continue
                if field[ny][nx] == '#':
                    mine += 1
            field[y][x] = str(mine)


def main(args):
    H, W = map(int, input().split())
    field = []
    for _ in range(H):
        temp = input().strip('\n')
        temp = list(temp)
        field.append(temp)

    result = solve(field, H, W)

    for r in field:
        print(''.join(r))


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

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
src = [input() for i in range(H)]

ans = []
for row in src:
    ans.append(list(row))

for i in range(H):
    for j in range(W):
        if src[i][j] == '#': continue
        c = 0
        if i > 0:
            if j > 0 and src[i-1][j-1] == '#': c += 1
            if src[i-1][j] == '#': c += 1
            if j < W-1 and src[i-1][j+1] == '#': c += 1
        if j > 0 and src[i][j-1] == '#': c += 1
        if j < W-1 and src[i][j+1] == '#': c += 1
        if i < H-1:
            if j > 0 and src[i+1][j-1] == '#': c += 1
            if src[i+1][j] == '#': c += 1
            if j < W-1 and src[i+1][j+1] == '#': c += 1
        ans[i][j] = c

for row in ans:
    print(''.join(list(map(str,row))))

Submission status: Accepted

Solution code:
# B
import numpy as np
H, W = map(int, input().split())

input_mat = np.zeros((H, W), dtype='int')
res_wide = np.zeros((H+2, W+2), dtype='int')

for i in range(H):
    line = list(input())
    for j in range(W):
        if line[j] == '#':
            res_wide[i  , j] += 1
            res_wide[i+1, j] += 1
            res_wide[i+2, j] += 1
            res_wide[i  , j+1] += 1
            input_mat[i, j] = 1
            res_wide[i+2, j+1] += 1
            res_wide[i  , j+2] += 1
            res_wide[i+1, j+2] += 1
            res_wide[i+2, j+2] += 1

for i in range(H):
    res_line = []
    for j in range(W):
        if input_mat[i, j] == 1:
            res_line.append('#')
        else:
            res_line.append(str(res_wide[i+1, j+1]))
    print("".join(res_line))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

import itertools


def inplace_convert(h, w, stage):
    for r0, c0 in itertools.product(range(h), range(w)):
        if stage[r0][c0] == ".":
            stage[r0][c0] = 0
            for dr, dc in itertools.product((-1, 0, 1), repeat=2):
                r, c = r0 + dr, c0 + dc
                if (r, c) != (r0, c0) and 0 <= r < h and 0 <= c < w:
                    cell = stage[r][c]
                    if cell == "#":
                        stage[r0][c0] += 1
            stage[r0][c0] = str(stage[r0][c0])


def main():
    h, w = (int(x) for x in input().split())
    stage = [list(input()) for _ in range(h)]
    inplace_convert(h, w, stage)
    print(*("".join(line) for line in stage), sep="\n")


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
H,W = map(int, input().split())

r = [-1,-1,-1,0,1,1,1,0]
c = [-1,0,1,1,1,0,-1,-1]

GRID = []

for i in range(H):
    Si = input()
    GRID.append(Si)

for i in range(H):
    for j in range(W):
        if GRID[i][j]=='#':
            print('#',end='')
        else:
            cnt = 0
            for k in range(8):
                ni = i + r[k]
                nj = j + c[k]

                if ni < 0 or ni >= H or nj < 0 or nj >= W:
                    continue

                if GRID[ni][nj]=='#':
                    cnt+=1
                    
            print(cnt,end='')

    print('\n',end='')

Submission status: Accepted

Solution code:
def solve():
    h, w = map(int, input().split())
    al = [list(input()) for _ in range(h)]
    ans = [[0 for _ in range(w)] for _ in range(h)]
    for i in range(h):
        for j in range(w):
            if al[i][j] == "#":
                ans[i][j] = "#"
                continue
            cnt = 0
            for k in range(-1, 2):
                for l in range(-1, 2):
                    if k == 0 and l == 0:
                        continue
                    if 0 <= i+k < h and 0 <= j+l < w:
                        if al[i+k][j+l] == "#":
                            cnt += 1
            ans[i][j] = str(cnt)
    for line in ans:
        print("".join(line))


if __name__=="__main__":
    solve()

Submission status: Accepted

Solution code:
H,W = map(int,raw_input().split(" "))
field = [raw_input() for i in range(H)]



def calc(h,w):
    res = 0
    for i in range(-1,2):
        for j in range(-1,2):
            nh = h + i
            nw = w + j
            
            if nh >= 0 and nh < H and nw >= 0 and nw < W and (not (nh == h and nw == w)):
                if field[nh][nw] == "#":
                    res+=1
    return res




for h,line in enumerate(field):
    newline = ""
    for w,c in enumerate(line):
        if c == "#":
            newline += "#"
        else:
            newline += str(calc(h,w))
    print newline

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
S = []
for i in range(H):
	S.append(list(input()))

ans = [['' for i in range(W)] for j in range(H)]
for i in range(H):
	for j in range(W):
		if S[i][j] == '#':
			ans[i][j] = '#'
			continue
		x = [1,1,1,0,0,-1,-1,-1]
		y = [1,0,-1,1,-1,1,0,-1]
		cnt = 0
		for k in range(len(x)):
			ii = i+x[k]
			jj = j+y[k]
			if 0 <= ii and ii < H and 0 <= jj and jj < W:
				if S[ii][jj] == '#':
					cnt += 1
		ans[i][j] = str(cnt)

for i in range(H):
	print(''.join(ans[i]))

Submission status: Accepted

Solution code:
H, W = map(int, raw_input().split())
s = []
for i in xrange(H):
  s.append(list(raw_input()))

for y in xrange(H):
  for x in xrange(W):
    if s[y][x] == '#':
      continue
    count = 0
    for dy in [-1, 0, 1]:
      for dx in [-1, 0, 1]:
        ny = y + dy
        nx = x + dx
        if 0 <= ny < H and 0 <= nx < W:
          if s[ny][nx] == '#':
            count += 1
    s[y][x] = str(count)

for i in xrange(H):
  print ''.join(s[i])

Submission status: Accepted

Solution code:
line1=input().split()
h=int(line1[0])
w=int(line1[1])
karta=[]
for i in range(h):
    karta.append(input())

out=[]
for i in range(h):
    out.append("")
    for j in range(w):
        if karta[i][j]=="#":
            out[i]+="#"
        else:
            count=0
            if i>0:
                if karta[i-1][j]=="#":
                    count+=1
                if j>0:
                    if karta[i-1][j-1]=="#":
                        count+=1
                if j<w-1:
                    if karta[i-1][j+1]=="#":
                        count+=1
            if i<h-1:
                if karta[i+1][j]=="#":
                    count+=1
                if j>0:
                    if karta[i+1][j-1]=="#":
                        count+=1
                if j<w-1:
                    if karta[i+1][j+1]=="#":
                        count+=1
            if j>0:
                if karta[i][j-1]=="#":
                    count+=1
            if j<w-1:
                if karta[i][j+1]=="#":
                    count+=1
            out[i]+=str(count)
for i in range(h):
    print(out[i])

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
f = [' ' * w] + [list(' ' + input().strip() + ' ') for _ in range(h)] + [' ' * w]

for i, l in enumerate(f):
    for j, b in enumerate(l):
        if b == '.':
            c = int(l[j - 1] == '#') + int(l[j + 1] == '#')
            c += f[i - 1][j - 1:j + 2].count('#')
            c += f[i + 1][j - 1:j + 2].count('#')
            l[j] = c
for l in f[1:h + 1]:
    print(''.join(map(str, l[1:w + 1])))

Submission status: Accepted

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

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

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()


def main():
    h,w = LI()
    a = [[0]*w for _ in range(h)]
    s = [S() for _ in range(h)]
    for i in range(h):
        si = s[i]
        for j in range(w):
            if si[j] != '#':
                continue
            if j < w-1:
                a[i][j+1] += 1
                if i < h-1:
                    a[i+1][j+1] += 1
                if i > 0:
                    a[i-1][j+1] += 1
            if j > 0:
                a[i][j-1] += 1
                if i < h-1:
                    a[i+1][j-1] += 1
                if i > 0:
                    a[i-1][j-1] += 1

            if i < h-1:
                a[i+1][j] += 1
            if i > 0:
                a[i-1][j] += 1

    for i in range(h):
        for j in range(w):
            if s[i][j] == '#':
                a[i][j] = '#'

    return '\n'.join([''.join(map(str, r)) for r in a])


print(main())

Submission status: Accepted

Solution code:
H,W = map(int, raw_input().split())
S = [raw_input() for y in range(H)]
A = [list(s) for s in S]
for y in range(H):
  for x in range(W):
    if S[y][x]!='#':
      c = 0
      for dx in range(-1,2):
        for dy in range(-1,2):
          if (dx,dy)!=(0,0) and 0<=x+dx<W and 0<=y+dy<H and S[y+dy][x+dx]=='#':
            c += 1
      A[y][x] = str(c)
for a in A:
  print ''.join(a)

Submission status: Accepted

Solution code:
from collections import defaultdict, Counter
from itertools import product, groupby, count, permutations, combinations
from math import pi, sqrt
from collections import deque
from bisect import bisect, bisect_left, bisect_right
INF = float("inf")


# 8近傍（右, 下, 左, 上，右上, 右下, 左下, 左上）
dy = [0, -1, 0, 1, 1, -1, -1, 1]
dx = [1, 0, -1, 0, 1, 1, -1, -1]

def inside(y: int, x: int, H: int, W: int) -> bool:
    return 0 <= y < H and 0 <= x < W

def main():
    H, W = map(int, input().split())
    f = []
    for _ in range(H):
        S = input()
        f.append(S)

    ans = [[0] * W for _ in range(H)]
    for y in range(H):
        for x in range(W):
            if f[y][x] == "#":
                ans[y][x] = "#"
            else:
                n = 0
                for i in range(8):
                    ny = y + dy[i]
                    nx = x + dx[i]
                    if inside(ny, nx, H, W) and f[ny][nx] == "#":
                        n += 1
                ans[y][x] = str(n)

    for line in ans:
        print(*line, sep="")

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
dxy = zip([1, 1, 0, -1, -1, -1, 0, 1], [0, 1, 1, 1, 0, -1, -1, -1])
H, W = map(int, raw_input().split())    
S = [list(raw_input()) for i in xrange(H)]

for y in xrange(H):
    for x in xrange(W):
        if S[y][x] == "#": continue
        tmp = 0
        for dx, dy in dxy:
            nx, ny = x + dx, y + dy
            if not (0 <= nx < W and 0 <= ny < H): continue
            tmp += 1 if S[ny][nx] == "#" else 0
        S[y][x] = str(tmp)

for s in S:
    print "".join(s)

Submission status: Accepted

Solution code:
import sys

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline()

n,m = na()
mp = []
for i in range(n):
    mp.append([_ for _ in ns().strip()])

for i in range(n):
    for j in range(m):
        if  mp[i][j] != '#':
            bo = 0
            for k in range(-1,2):
                for l in range(-1,2):
                    ni = i + k
                    nj = j + l
                    if 0 <= ni < n and 0 <= nj < m and mp[ni][nj] == '#':
                        bo += 1
            mp[i][j] = chr(bo + 48)

for i in mp:
    print("".join(i))

Submission status: Accepted

Solution code:
H, W = map(int, raw_input().split())
A = [raw_input() for _ in xrange(H)]
B = [[0 for j in xrange(W)] for i in xrange(H)]

dr = [-1, 0, 1, -1, 1, -1, 0, 1]
dc = [-1, -1, -1, 0, 0, 1, 1, 1]


for i in xrange(H):
    for j in xrange(W):
        if A[i][j] == '#':
            B[i][j] = '#'
            continue
        for k in xrange(8):
            ni = i + dr[k]
            nj = j + dc[k]
            if ni < 0 or ni >= H or nj < 0 or nj >= W:
                continue
            if A[ni][nj] == '#':
                B[i][j] += 1

for i in xrange(H):
    print ''.join(map(str, B[i]))

Submission status: Runtime Error

Solution code:

import numpy as np

h,w = map(int,(input().split()))
s = [list(map(str,input())) for i in range(h)]
l = [[0]*(w+2) for i in range(h+2)]


def addFlag(i,j):
    for x in range(3):
        for y in range(3):
            if l[i+x][j+y] != '#':
                l[i+x][j+y] += 1
                
for i in range(h):
    for j in range(w):
        if s[i][j] == '#':
            l[i+1][j+1] = '#'
            addFlag(i,j)

l = np.delete(l,[0,h+1],0)
l = np.delete(l,[0,w+1],1)

for i in l:
    if len(i)>1:
        ans = ''.join(i)
    else:
        ans = int(i)
    print(ans)

Submission status: Runtime Error

Solution code:
import numpy as np

h,w = map(int,(input().split()))
s = [list(map(str,input())) for i in range(h)]
l = [[0]*(w+2) for i in range(h+2)]


def addFlag(i,j):
    for x in range(3):
        for y in range(3):
            if l[i+x][j+y] != '#':
                l[i+x][j+y] += 1
                
for i in range(h):
    for j in range(w):
        if s[i][j] == '#':
            l[i+1][j+1] = '#'
            addFlag(i,j)

l = np.delete(l,[0,h+1],0)
l = np.delete(l,[0,w+1],1)

for i in l:
    if len(i)>1:
        ans = ''.join(i)
    else:
        ans = print(*i)
    print(ans)

Submission status: Runtime Error

Solution code:

import numpy as np

h,w = map(int,(input().split()))
s = [list(map(str,input())) for i in range(h)]
l = [[0]*(w+2) for i in range(h+2)]


def addFlag(i,j):
    for x in range(3):
        for y in range(3):
            if l[i+x][j+y] != '#':
                l[i+x][j+y] += 1
                
for i in range(h):
    for j in range(w):
        if s[i][j] == '#':
            l[i+1][j+1] = '#'
            addFlag(i,j)

l = np.delete(l,[0,h+1],0)
l = np.delete(l,[0,w+1],1)

for i in l:
    if len(i)>1:
        ans = ''.join(i)
    else:
        ans = i
    print(*ans)

Submission status: Runtime Error

Solution code:
import numpy as np

h,w = map(int,(input().split()))
s = [list(map(str,input())) for i in range(h)]
l = [[0]*(w+2) for i in range(h+2)]


def addFlag(i,j):
    for x in range(3):
        for y in range(3):
            if l[i+x][j+y] != '#':
                l[i+x][j+y] += 1
                
for i in range(h):
    for j in range(w):
        if s[i][j] == '#':
            l[i+1][j+1] = '#'
            addFlag(i,j)

l = np.delete(l,[0,h+1],0)
l = np.delete(l,[0,w+1],1)

for i in l:
    ans = ''.join(i)
    print(ans)

Submission status: Runtime Error

Solution code:
h, w = map(int, input().split())
field = [list(input().split()) for _ in range(h)]
dx = [1, 0, -1, 0, 1, -1, -1, 1]
dy = [0, 1, 0, -1, 1, 1, -1, -1]
for i in range(h):
    for j in range(w):
        if field[i][j] != "#":
            num = 0
            for k in range(8):
                ni = i + dy[k]
                nj = j + dx[k]
                if nj < 0 or h <= nj:
                    continue
                if ni < 0 or w <= ni:
                    continue
                if field[ni][nj] == "#":
                    num += 1
            field[i][j] = num
for out in field:
    print("".join(out))

Submission status: Runtime Error

Solution code:
h,w = map(int,input().split())
s = [list(map(str,input())) for _ in range(h)]
for i in range(h):
  for j in range(w):
    if s[i][j] == ".":
      if i == 0 and j == 0:
        s[i][j] = str([s[0][1],s[1][0],s[1][1]].count("#"))
      elif i == 0 and j == w-1:
        s[i][j] = str([s[i][j-1],s[i+1][j-1],s[i+1][j]].count("#"))
      elif i == h-1 and j == 0:
        s[i][j] = str([s[i-1][0],s[i-1][1],s[i][1]].count("#"))
      elif i == h-1 and j == w-1:
        s[i][j] = str([s[i-1][j-1],s[i-1][j],s[i][j-1]].count("#"))
      elif i == 0:
        s[i][j] = str([s[i][j-1],s[i][j+1],s[i+1][j-1],s[i+1][j],s[i+1][j+1]].count("#"))
      elif i == h-1:
        s[i][j] = str([s[i][j-1],s[i][j+1],s[i-1][j-1],s[i-1][j],s[i-1][j+1]].count("#"))
      elif j == 0:
        s[i][j] = str([s[i-1][j],s[i+1][j],s[i-1][j+1],s[i][j+1],s[i+1][j+1]].count("#"))
      elif j == w-1:
        s[i][j] = str([s[i-1][j],s[i+1][j],s[i-1][j-1],s[i][j-1],s[i+1][j-1]].count("#"))
      else:
        s[i][j] = str([s[i-1][j-1],s[i-1][j],s[i-1][j+1],s[i][j-1],s[i][j+1],s[i+1][j-1],s[i+1][j],s[i+1][j+1]].count("#"))

for i in range(h):
  print("".join(s[i]))