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:
import numpy as np

h, w = map(int, input().split())
s = [list(input()) for _ in range(h)]
f = np.zeros((h+2, w+2), dtype='int64')
d = np.ones((3, 3), dtype='int64')

for i in range(h):
    for j in range(w):
        if s[i][j] == '#':
            f[i:i+3, j:j+3] += d 

for i in range(h):
    ans = ''
    for j in range(w):
        if s[i][j] == '#':
            ans += '#'
        else:
            ans += str(f[i+1, j+1])
    print(ans)

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
grid = [list(input()) for _ in range(H)]
H -= 1
W -= 1
for h, line in enumerate(grid[:]):
    hs = h,
    if 0 < h:
        hs += h - 1,
    if h < H:
        hs += h + 1,
    for w, g in enumerate(line):
        if g == '#':
            continue
        ws = w,
        if 0 < w:
            ws += w - 1,
        if w < W:
            ws += w + 1,
        c = 0
        for y in hs:
            for x in ws:
                if grid[y][x] == '#':
                    c += 1
        grid[h][w] = c
print(*map(lambda x: ''.join(map(str, x)), grid), sep='\n')

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
ans=[["."]*(w+2)]
for i in range(h):
  temp=list(map(str,input()))
  temp.insert(0,".")
  temp.append(".")
  ans.append(temp)
ans.append(["."]*(w+2))
for i in range(1,h+1):
  for j in range(1,w+1):
    if ans[i][j]==".":
      temp=0
      for k in range(3):
        for l in range(3):
          if ans[i-1+k][j-1+l]=="#":
            temp=temp+1
      ans[i][j]=str(temp)
for i in range(1,h+1):
  del ans[i][0]
  del ans[i][w]
  print("".join(ans[i]))

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
s = [list(input()) for _ in range(h)]
f = [[0] * (w+2) for _ in range(h+2)]
d = [(-1, 1), (-1, 0), (-1, -1), (0, 1), (0, -1), (1, 1), (1, 0), (1, -1)]

for i in range(h):
    for j in range(w):
        if s[i][j] == '#':
            for x, y in d:
                f[i+1+x][j+1+y] += 1

for i in range(h):
    ans = ''
    for j in range(w):
        if s[i][j] == '#':
            ans += '#'
        else:
            ans += str(f[i+1][j+1])
    print(ans)

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
A=["o"*(W+2)]+["o"+input()+"o" for i in range(H)]+["o"*(W+2)]
for i in range(1,H+1):
    B=""
    for j in range(1,W+1):
        count=0
        if A[i][j]==".":
            if A[i-1][j]=="#":
                count+=1
            if A[i+1][j]=="#":
                count+=1
            if A[i][j+1] == "#":
                count += 1
            if A[i][j-1] == "#":
                count += 1
            if A[i-1][j+1]=="#":
                count+=1
            if A[i-1][j-1]=="#":
                count+=1
            if A[i+1][j-1]=="#":
                count+=1
            if A[i+1][j+1]=="#":
                count+=1
            B+=str(count)
        else:
            B+="#"
    print(B)

Submission status: Accepted

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

s = []
for i in range(h):
	t = input()
	s.append(t)

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

ans = []
for i in range(h):
	v = ""
	for j in range(w):
		if s[i][j] == "#":
			v += "#"
		else:
			c = 0
			for k in range(8):
				x = i + dx[k]
				y = j + dy[k]
				if x < 0 or x >= h or y < 0 or y >= w:
					continue
				if s[x][y] == "#":
					c += 1
			v += str(c)
	ans.append(v)

for i in range(h):
	print (ans[i])

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
field = [input() for i in range(h)]
AX = [1, 1, 0, -1, -1, -1, 0, 1]
AY = [0, 1, 1, 1, 0, -1, -1, -1]
ANS = [''] * h
for y in range(h):
	for x in range(w):
		if field[y][x] == '#':
			ANS[y] += '#'
		else:
			count = 0
			for dy, dx in zip(AY, AX):
				ny = y + dy
				nx = x + dx
				if not 0 <= ny < h:
					continue
				if not 0 <= nx < w:
					continue
				if field[ny][nx] == '#':
					count += 1
			ANS[y] += str(count)
for s in ANS:
	print(s)

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
S = [input() for i in range(h)]
dx = [1, 1, 0, -1, -1, -1, 0, 1]
dy = [0, 1, 1, 1, 0, -1, -1, -1]
ANS = []
for y in range(h):
	s = ''
	for x in range(w):
		if S[y][x] == '#':
			s += '#'
		else:
			count = 0
			for di in range(8):
				ny = y + dy[di]
				nx = x + dx[di]
				if ny < 0 or nx < 0 or ny >= h or nx >= w:
					continue
				if S[ny][nx] == '#':
					count += 1
			s += str(count)
	ANS.append(s)
for i in range(h):
	print(ANS[i])

Submission status: Accepted

Solution code:
from itertools import product

H, W = map(int, input().split())
S = [list(input()) for _ in range(H)]
D = tuple(product((-1, 0, 1), repeat=2))

for h in range(H):
    for w in range(W):
        if S[h][w] == '#':
            continue
        cnt = 0
        for dh, dw in D:
            if 0 <= h + dh < H and 0 <= w + dw < W and S[h + dh][w + dw] == '#':
                cnt += 1
        S[h][w] = str(cnt)

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

Submission status: Accepted

Solution code:
h,w = map(int,input().split())
s = [[0]*(w+2)]+[[0]+[(i == "#")*1 for i in list(input())]+[0] for _ in range(h)]+[[0]*(w+2)]

ans = [[0]*w for _ in range(h)]
for i in range(h):
    for j in range(w):
        if s[i+1][j+1] == 1:
            ans[i][j] = "#"
            continue
        ans[i][j] = str(s[i][j+1]+s[i+1][j]+s[i+1][j+2]+s[i+2][j+1]+s[i][j]+s[i+2][j+2]+s[i+2][j]+s[i][j+2])
for l in ans:
    print("".join(l))

Submission status: Accepted

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

dh = [-1,-1,-1,0,0,1,1,1]
dw = [-1,0,1,-1,1,-1,0,1]

for i in range(H):
  for j in range(W):
    count=0
    if S[i][j]==".":
      for l in range(8):
        if H>i+dh[l]>-1 and W>j+dw[l]>-1:
          if S[i+dh[l]][j+dw[l]]=="#":
            count+=1
      S[i]=S[i][:j] + str(count) + S[i][j+1:]

for i in range(H):
  print(S[i])

Submission status: Accepted

Solution code:

def count_adjacent_bombs(expanded_grid, i, j):
  dx = [-1, 0, 1, -1, 1, -1, 0, 1]
  dy = [1, 1, 1, 0, 0, -1, -1, -1]
  bombs = 0
  for ind in range(8):
    if expanded_grid[i+dx[ind]][j+dy[ind]] == '#':
      bombs += 1
  return bombs


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

expanded_grid = []
expanded_grid.append('.' * (w+2))
for i in range(h):
  expanded_grid.append('.' + grid[i] + '.')
expanded_grid.append('.' * (w+2))


for i in range(1, h+1):
  for j in range(1, w+1):
    if expanded_grid[i][j] == '#':
      print('#', end='')
    else:
      print(count_adjacent_bombs(expanded_grid, i, j), end='')
  print('')

Submission status: Accepted

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

for i in range(H):
    for j in range(W):
        c = 0
        #「#」かどうか
        if s[i][j] == '#':
            continue
        #左上
        if 0 < i and 0 < j and s[i-1][j-1] == '#':
            c += 1
        #中上
        if 0 < i and s[i-1][j] == '#':
            c += 1
        #右上
        if 0 < i and j < W-1 and s[i-1][j+1] == '#':
            c += 1
        #左横
        if  0 < j and s[i][j-1] == '#':
            c += 1
        #右横
        if j < W-1 and s[i][j+1] == '#':
            c += 1
        #左下
        if  0 < j and i < H-1 and s[i+1][j-1] == '#':
            c += 1
        #中下
        if i < H-1 and s[i+1][j] == '#':
            c += 1
        #右下
        if i < H-1 and j < W-1 and s[i+1][j+1] == '#':
            c += 1
        s[i][j] = str(c)
for i in range(H):
    print(''.join(s[i]))

Submission status: Accepted

Solution code:
h, w = (int(i) for i in input().split())
A = [None] * h
for i in range(h):
    A[i] = list(input())

for i in range(h):
    for j in range(w):
        cnt = 0
        if A[i][j] == '.':
            for s in range(-1, 2):
                for t in range(-1, 2):
                    if i+s >= 0 and i+s < h and j+t >= 0 and j+t < w:
                        if A[i+s][j+t] == '#': cnt += 1
            A[i][j] = cnt
            print(cnt, end='')
        else:
            print('#', end='')
    print()

Submission status: Accepted

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

# 上下左右斜め方向への移動に使う
dx = [-1, -1, -1, 0, 0, 1, 1, 1]
dy = [-1, 0, 1, -1, 1, -1, 0, 1]

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

        num = 0
        for k in range(8):
            ni = i + dx[k]
            nj = j + dy[k]
            # 上下はみ出してたら何もせん
            if ni < 0 or h <= ni: continue
            # 左右はみ出してたら何もせん
            if nj < 0 or w <= nj: continue
            # はみだしてなかったらそこ見て#やったら1増やす
            if s[ni][nj] == '#': num += 1
        
        s[i][j] = str(num)
    
for i in range(h):
    print(''.join(s[i]))

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
m = [[0] for i in range(H+2)]
m[0] += [0]*W + [0]
for i in range(1,H+1):
  m[i]+=list(input().replace('.','0')) + [0]
m[H+1]+= [0]*W + [0]


for i in range(1,H+1):
  ans=''
  for j in range(1,W+1):
    if m[i][j] != '#':
      count = 0
      if m[i-1][j-1]=='#':count+=1
      if m[i-1][j  ]=='#':count+=1
      if m[i-1][j+1]=='#':count+=1
      if m[i  ][j-1]=='#':count+=1
      if m[i  ][j+1]=='#':count+=1
      if m[i+1][j-1]=='#':count+=1
      if m[i+1][j  ]=='#':count+=1
      if m[i+1][j+1]=='#':count+=1
      m[i][j] = count
    ans+=str(m[i][j])
  print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Wed May 27 16:14:37 2020

@author: naoki
"""

H,W = map(int,input().split()) # 行の数Hと列の数Wを入力
moji = [input() for i in range(H)] # H*Wの文字列を入力
s = [str(0) for i in range(W+2)]
string1 = "".join(s) # 全て0で長さW+２の文字列を作成
string = [string1]
for i in range(H):
    moji[i] ="0" + moji[i] + "0" # 端の部分を0で埋める
moji = string + moji + string # ０行目に0のみの文字列を追加する 最後の行にも0のみの文字列を追加する
dx = [-1,-1,-1,0,0,1,1,1]
dy = [-1,0,1,-1,1,-1,0,1] # 8方位の配列を用意
count = [[0 for i in range(W+2)] for j in range(H+2)] 
new_list2 = [[str(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 moji[i][j] == ".": # .の場合には以下の処理を実行
            for k in range(8):
                if moji[i+dy[k]][j+dx[k]] ==  "#": # "#"の個数によって加算する
                    count[i][j]+=1
         # "#"の場合には処理を実行しない 

for i in range(1,H+1):
    for j in range(1,W+1):
        new_list = list(moji[i]) # i行目の文字列を一旦リストに変換し該当箇所を数字に変換
        if new_list[j] == ".": # j文字目が　.ならば数字を代入  
           new_list2[i][j] = str(count[i][j])    
        else: # j文字目が # ならばそのまま代入
           new_list2[i][j] = str("#") 
    new_string = "".join(new_list2[i])
    print(new_string[1:W+1])

Submission status: Accepted

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

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

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

        num = 0
        for k in range(8):
            ni = i + dx[k]
            nj = j + dy[k]

            if ni < 0 or h <= ni: continue
            if nj < 0 or w <= nj: continue
            if s[ni][nj] == '#': num += 1
        
        s[i][j] = str(num)
    
for i in range(h):
    print(''.join(s[i]))

Submission status: Accepted

Solution code:
def search(y,x):
    if 0<=y<=h-1 and 0<=x<=w-1:
        if s[y][x]=="#":
            return 1
        else:
            return 0
    else:
        return 0
h,w = map(int,input().split())
s = [list(input()) for i in range(h)]
m = [[-1]*w for i in range(h)]
for y in range(h):
    for x in range(w):
        si = s[y][x]
        n = 0
        n+=search(y+1,x)
        n+=search(y+1,x+1)
        n+=search(y+1,x-1)
        n+=search(y-1,x-1)
        n+=search(y-1,x)
        n+=search(y-1,x+1)
        n+=search(y,x-1)
        n+=search(y,x+1)
        
        m[y][x]=n
for y in range(h):
    for x in range(w):
        si = s[y][x]
        if si=="#":
            m[y][x]="#"
for mi in m:
    print("".join([str(i) for i in mi]))

Submission status: Accepted

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

for i in range(H):
    for j in range(W):
        if S[i][j] == '.':
            cnt = 0
            for k in range(-1, 2):
                for l in range(-1, 2):
                    x = i + k
                    y = j + l
                    if 0 <= x < H and 0 <= y < W and S[x][y] == '#':
                        cnt += 1
            S[i][j] = cnt
            
for i in range(H):
    print(''.join(map(str, S[i])))

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
s = [list(input()) for i in range(H)]
n = [[0]*(W+2) for i in range(H+2)]
dxy = [(-1,-1),(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1)]

for h in range(H):
  for w in range(W):
    if s[h][w] == '#':
      for i in dxy:
        n[h + 1 + i[0]][w + 1 + i[1]] += 1

for i in range(H):
  for j in range(W):
    if s[i][j] == '#':
      n[i + 1][j + 1] = '#'
    else:
      n[i + 1][j + 1] = str(n[i + 1][j + 1])

for a in n[1:H+1]:
    print(''.join(a[1:W+1]))

Submission status: Accepted

Solution code:

def main():
    H,W = map(int, input().split())  
    M=[]
    x = [1,0,-1,0,1,-1,1,-1]
    y = [0,1,0,-1,1,-1,-1,1]
    for i in range(H):
        M.append(input())
    
    for i in range(H):
        for j in range(W):
            if M[i][j]=='.':
                cnt=0
                for k in range(8):
                    cx = j + x[k]
                    cy = i + y[k]
                    if cx >=0 and cx < W and cy>=0 and cy <H:
                        if M[cy][cx] == '#':
                            cnt+=1
                str_list = list(M[i])
                str_list[j] = str(cnt)
                str_changed = "".join(str_list)
                M[i] = "".join(str_list)
        
    for i in range(H):
        print(M[i])



if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import copy
H, W = map(int, input().split())
S = [list(input()) for _ in range(H)]
S_result = [[0]*(W+2) for _ in range(H+2)]

dx = [-1,-1,-1,0,0,1,1,1]
dy = [-1,0,1,-1,1,-1,0,1]
for i in range(H):
    for j in range(W):
        if S[i][j] == "#":
            for x,y in zip(dx,dy):
                if S_result[i+y+1][j+x+1] != "#":
                    S_result[i+y+1][j+x+1] += 1
            S_result[i+1][j+1] = "#"
            
for h in S_result[1:H+1]:
    print("".join(map(str, h[1:W+1])))

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
s=[list(input()) for _ in range(h)]
l=[]
l.append(['*']*(w+1))
for i in range(h):
    l1=s[i]
    l1.insert(0,'*')
    l1.append('*')
    l.append(l1)
l.append(['*']*(w+1))

for i in range(1,h+1):
    for j in range(1,w+1):
        c=0
        if l[i][j]=='.':
            c+=l[i-1][j-1:j+2].count('#')
            c+=l[i][j-1:j+2].count('#')
            c+=l[i+1][j-1:j+2].count('#')
            l[i].pop(j)
            l[i].insert(j,str(c))
            
for i in range(1,h+1):
    print(''.join(l[i][1:w+1]))

Submission status: Accepted

Solution code:
def main():
    H, W = map(int, input().split())
    board = [list(input()) for _ in range(H)]
    new_board = []
    for i in range(H):
        new_line = ""
        for j in range(W):
            num_bomb = 0
            if board[i][j] != "#":
                for k in range(-1, 2):
                    for l in range(-1, 2):
                        idx1, idx2 = i+k, j+l
                        if idx1 >= 0 and idx2 >= 0 and idx1 < H and idx2 < W:
                            item = board[i+k][j+l]
                            if item == "#":
                                num_bomb += 1
                new_line += str(num_bomb)
            else:
                new_line += "#"

        new_board.append(new_line)

    for i in range(H):
        print(new_board[i])


if __name__ == '__main__':
    main()

Submission status: Accepted

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

DX=[-1,0,1]
DY=[-1,0,1]

for i in range(H):
  for j in range(W):
    if S[i][j]=='#':
      for dy in DY:
        for dx in DX:
          if dx==0 and dy==0:
            continue
          x = j+dx
          y = i+dy
          if 0<=x<W and 0<=y<H:
            if S[y][x]=='.':
              S[y][x]=1
            elif S[y][x]!='#':
              S[y][x]+=1

for i in range(H):
  for j in range(W):
    if S[i][j]=='.':
      S[i][j]=0
    S[i][j]=str(S[i][j])
for i in S:
  print(''.join(i))

Submission status: Accepted

Solution code:
import sys

a = sys.stdin.readline().split(' ')
data = sys.stdin.readlines()

S = int(a[0])
H = int(a[1])

for i in range(len(data)):
    data[i] = [j.replace('\n', '') for j in data[i]]

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

if S == 1 and H == 1:
    if data[0][0] == ".":
        data[0][0] = str(0)

for i in range(S):
    for j in range(H):
        if data[i][j] == '#':
            continue
        else:
            count = 0
            for k in range(8):
                x = j + dx[k]
                y = i + dy[k]
                if x < 0 or x >=H or y < 0 or y >= S:
                    continue
                elif data[y][x] == "#":
                    count = count+1
                data[i][j] = str(count)

for i in range(len(data)):
    print(str(data[i]).replace('[', '').replace(']', '').replace(',', '').replace("'", '').replace(' ', ''))

Submission status: Accepted

Solution code:
import sys


def input(): return sys.stdin.readline().strip()


def resolve():
    H, W = map(int, input().split())
    l = [list(input()) for i in range(H)]
    cl = [[0] * W for i in range(H)]
    for h in range(H):
        for w in range(W):
            if l[h][w] == '#':
                cl[h][w]='#'
                for j, k in ([1,-1],[1, 0],[1,1], [-1,-1],[-1, 0],[-1,1], [0, 1], [0, -1]):
                    nh, nw = h + j, w + k
                    if nh < 0 or nh >= H or \
                            nw < 0 or nw >= W:
                        continue
                    else:
                        if cl[nh][nw]!='#':
                            cl[nh][nw]+=1
    for x in cl:
        print(*x,sep='')
resolve()

Submission status: Accepted

Solution code:
import sys


def input(): return sys.stdin.readline().strip()


def resolve():
    H, W = map(int, input().split())
    l = [list(input()) for i in range(H)]
    cl = [[0] * W for i in range(H)]
    for h in range(H):
        for w in range(W):
            if l[h][w] == '#':
                cl[h][w]='#'
                for j, k in ([1,-1],[1, 0],[1,1], [-1,-1],[-1, 0],[-1,1], [0, 1], [0, -1]):
                    nh, nw = h + j, w + k
                    if nh < 0 or nh >= H or \
                            nw < 0 or nw >= W:
                        continue
                    else:
                        if cl[nh][nw]!='#':
                            cl[nh][nw]+=1
    for h in range(H):
        ans=''
        for x in cl[h]:
            ans+=str(x)
        print(ans)
resolve()

Submission status: Accepted

Solution code:
H, W=map(int, input().split())
A= [list(input()) for _ in range(H)]
B = [[0]*W for _ in range(H)]
nx = [1,1,1,0,0,-1,-1,-1]
ny = [-1, 0, 1, -1, 1, -1, 0, 1]
for i in range(H):
  for j in range(W):
    if A[i][j] == "#":
      B[i][j] = "#"
    else:
      c = 0
      for k in range(8):
        newx = i+nx[k]
        newy = j+ny[k]
        if 0<= newx <= H-1 and 0<= newy <= W-1:
          if A[newx][newy] == "#":
            c += 1
      B[i][j] = str(c)
C=[0]*H
for i in range(H):
    C[i] = "".join(B[i])
for i in range(H):
  print(C[i])

Submission status: Accepted

Solution code:
import sys


def input(): return sys.stdin.readline().strip()


def resolve():
    H, W = map(int, input().split())
    l = [list(input()) for i in range(H)]
    cl = [[0] * (W + 2) for i in range(H + 2)]
    for h in range(H):
        for w in range(W):
            if l[h][w] == '#':
                cl[h + 1][w + 1] = '#'
                if cl[h][w] != '#':
                    cl[h][w] += 1
                if cl[h][w + 1] != '#':
                    cl[h][w + 1] += 1
                if cl[h][w + 2] != '#':
                    cl[h][w + 2] += 1

                if cl[h + 1][w + 2] != '#':
                    cl[h + 1][w + 2] += 1
                if cl[h + 1][w] != '#':
                    cl[h + 1][w] += 1

                if cl[h + 2][w] != '#':
                    cl[h + 2][w] += 1
                if cl[h + 2][w] != '#':
                    cl[h + 2][w + 1] += 1
                if cl[h + 2][w + 2] != '#':
                    cl[h + 2][w + 2] += 1
    for h in range(1, H + 1):
        ans=''
        for x in cl[h][1:-1]:
            ans+=str(x)
        print(ans)

resolve()

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
a=[['x']*(w+2)]
for i in range(h):
  tmp = ['x']
  tmp.extend(list(map(str,input())))
  tmp.append('x')
  a.append(tmp)
a.extend([['x']*(w+2)])
ans= []
for i in range(1,h+1):
  tmp=[]
  for j in range(1,w+1):
    if a[i][j] == '#':
      tmp.append('#')
    else:
      tmp.append([a[i-1][j-1],a[i-1][j],a[i-1][j+1],a[i][j-1],a[i][j+1],a[i+1][j-1],a[i+1][j],a[i+1][j+1]].count('#'))
  ans.append(tmp)
for i in range(h):
  print(*ans[i],sep='')

Submission status: Accepted

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


def solve(H: int, W: int, S: "List[str]"):
    DH = (1, 1, 1, 0, 0, -1, -1, -1)
    DW = (-1, 0, 1, -1, 1, -1, 0, 1)
    ans = [['#'] * W for _ in range(H)]
    for h in range(H):
        for w in range(W):
            if S[h][w] == '#':
                continue
            t = 0
            for dh, dw in zip(DH, DW):
                nh, nw = h + dh, w + dw
                if not(0 <= nh < H and 0 <= nw < W):
                    continue
                if S[nh][nw] == '#':
                    t += 1
            ans[h][w] = str(t)
    for a in ans:
        print(''.join(a))

# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    H = int(next(tokens))  # type: int
    W = int(next(tokens))  # type: int
    S = [next(tokens) for _ in range(H)]  # type: "List[str]"
    solve(H, W, S)

def test():
    import doctest
    doctest.testmod()

if __name__ == '__main__':
    #test()
    main()

Submission status: Accepted

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

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

for i in range(h):
    for j in range(w):
        if s[i][j] == '#':
            continue
        elif s[i][j] == '.':
            num = 0
            for a in range(8):
                ni = i + dx[a]
                nj = j + dy[a]

                if (0 <= ni < h) and (0 <= nj < w) and (s[ni][nj] == '#'):
                    num += 1
            s[i][j] = num

[print(*i,sep='') for i in s]

Submission status: Accepted

Solution code:
import sys
import collections

size = sys.stdin.readline().split(' ')
S = int(size[0])
H = int(size[1])


data = sys.stdin.readlines()
for i in range(len(data)):
	data[i] = [j.replace('\n','') for j in data[i]]


if S == 1 and H == 1:
	if data[0][0] == ".":
		data[0][0] = "0"
elif S == 1 and H > 1:
	for j in range(H):
		if data[0][j] == "#":
			continue
		else:
			if j == 0:
				list = [data[0][j+1]]
				count = str(list.count("#"))
				data[0][j] = count
			elif j == (H-1):
				list = [data[0][j-1]]
				count = str(list.count("#"))
				data[0][j] = count
			else:
				list = [data[0][j-1], data[0][j+1]]
				count = str(list.count("#"))
				data[0][j] = count
elif S > 1 and H == 1:
	for i in range(S):
		if data[i][0] == "#":
			continue
		else:
			if i == 0:
				list = [data[i+1][0]]
				count = str(list.count("#"))
				data[i][0] = count
			elif i == (S-1):
				list = [data[i-1][0]]
				count = str(list.count("#"))
				data[i][0] = count	
			else:
				list = [data[i-1][0], data[i+1][0]]
				count = str(list.count("#"))
				data[i][0] = count					
else:
	for i in range(S):
		for j in range(H):
			if data[i][j] == "#":
				continue
			else:
				#上左
				if i == 0 and j == 0:
					list = [data[i+1][j], data[i+1][j+1], data[i][j+1]]
					count = str(list.count("#"))
					data[i][j] = count
				#下右
				elif i == (S-1) and j == (H-1):
					list = [data[i-1][j], data[i-1][j-1], data[i][j-1]]
					count = str(list.count("#"))
					data[i][j] = count
				# 上右
				elif i == 0 and j == (H-1):
					list = [data[i][j-1], data[i+1][j-1], data[i+1][j]]
					count = str(list.count("#"))
					data[i][j] = count
				# 下左
				elif i == (S-1) and j == 0:
					list = [data[i-1][j], data[i-1][j+1], data[i][j+1]]
					count = str(list.count("#"))
					data[i][j] = count
				# 左
				elif (1 <= i < (S-1)) and j == 0:
					list = [data[i-1][j], data[i-1][j+1], data[i][j+1], data[i+1][j+1], data[i+1][j]]
					count = str(list.count("#"))
					data[i][j] = count
				# 右
				elif (1 <= i < (S-1)) and j == (H-1):
					list = [data[i-1][j], data[i-1][j-1], data[i][j-1], data[i+1][j-1], data[i+1][j]]
					count = str(list.count("#"))
					data[i][j] = count
				# 上
				elif i == 0 and (1<= j < (H-1)):
					list = [data[i][j-1], data[i+1][j-1], data[i+1][j], data[i+1][j+1], data[i][j+1]]
					count = str(list.count("#"))
					data[i][j] = count
				# 下
				elif i == (S-1) and (1<= j < (H-1)):
					list = [data[i][j-1], data[i-1][j-1], data[i-1][j], data[i-1][j+1], data[i][j+1]]
					count = str(list.count("#"))
					data[i][j] = count
				# 真ん中
				else:
					list = [data[i][j-1], data[i-1][j-1],data[i-1][j],data[i-1][j+1],data[i][j+1],data[i+1][j+1],data[i+1][j],data[i+1][j-1]]
					count = str(list.count("#"))
					data[i][j] = count



for i in range(len(data)):
	ans = str(data[i]).replace('[', '').replace(']', '').replace(',', '').replace("'", '').replace(' ', '')
	print(ans)

Submission status: Accepted

Solution code:
h,w = map(int,input().split())
masume = [list(["."] for _ in range(w+2))]

for i in range(h):
    masume.append(list(["."]+list(input())+["."]))
    
masume.append(list(["."] for _ in range(w+2)))

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

for i in range(1,h+1):
    for j in range(1,w+1):
        count_mine = 0
        
        if masume[i][j] == ".":
            for k in range(8):
                if masume[i+dy[k]][j+dx[k]] == "#":
                    count_mine += 1

            masume[i][j] = str(count_mine)
            
for i in range(1,h+1):
    print(*masume[i][1:-1],sep="")

Submission status: Accepted

Solution code:
# 下、右、上、左、右下、右上、左下、左上
dx = [0, 1, 0, -1, 1, 1, -1, -1]
dy = [1, 0, -1, 0, 1, -1, 1, -1]

h, w = map(int, input().split())

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

for y in range(h):
    for x in range(w):

        if l[y][x] == '#':
            continue

        cnt = 0

        for k in range(8):
            nx = x + dx[k]
            ny = y + dy[k]

            if nx < 0 or w <= nx or ny < 0 or h <= ny:
                continue

            if l[ny][nx] == '#':
                cnt += 1

        l[y][x] = str(cnt)

for y in range(h):
    print(''.join(l[y]))

Submission status: Accepted

Solution code:
H,W = map(int, input().split())
grid = []
grid.append(["."]*(W+2))
for i in range(H):
    s = ["."]+list(input())+["."]
    grid.append(s)
grid.append(["."]*(W+2))
for i in range(1,H+1):
    for j in range(1,W+1):
        if grid[i][j] != "#":
            temp = [grid[i-1][j-1],grid[i-1][j],grid[i-1][j+1],grid[i][j-1],grid[i][j+1],grid[i+1][j-1],grid[i+1][j],grid[i+1][j+1]]
            bom = str(temp.count("#"))
            grid[i][j] = bom
for i in range(1,H+1):
    print("".join(grid[i][1:W+1]))

Submission status: Accepted

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


def solve(H: int, W: int, S: "List[str]"):
    M = [[0 for j in range(W)] for i in range(H)]

    for h in range(H):
        for w in range(W):
            if S[h][w] is "#":
                M[h][w] = -1

    for h in range(H):
        for w in range(W):

            if M[h][w] !=  -1:
                continue

            for hi in [-1,0,1]:

                if not (0 <= h+hi < H):
                    continue

                for wi in [-1,0,1]:

                    if not (0 <= w+wi < W):
                        continue
                        
                    val = M[h+hi][w+wi]
                    if val == -1:
                        continue
                    else:
                        M[h+hi][w+wi] += 1

    for h in range(H):
        print( "".join( [ "#" if w == -1 else str(w) for w in M[h] ] ) )
    return


# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    H = int(next(tokens))  # type: int
    W = int(next(tokens))  # type: int
    S = [next(tokens) for _ in range(H)]  # type: "List[str]"
    solve(H, W, S)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

# 下、右、上、左、右下、右上、左下、左上


def dfs8(y, x):
    dy = [1, 0, -1, 0, 1, -1, 1, -1]
    dx = [0, 1, 0, -1, 1, 1, -1, -1]
    cnt = 0
    for k in range(8):
        ny = y + dy[k]
        nx = x + dx[k]
        if ny < 0 or H <= ny or nx < 0 or W <= nx:
            continue
        if field[ny][nx] == '#':
            cnt += 1
    return str(cnt)


H, W = map(int, readline().split())
field = [list(readline().decode())for _ in range(H)]
for y in range(H):
    for x in range(W):
        if field[y][x] != '#':
            field[y][x] = dfs8(y, x)
    print("".join(field[y]))