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())
s = [list(input()) for i in range(h)]

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

for y in range(h):
    for x in range(w):
        if s[y][x] != '.':
            continue
        p_sum = 0
        for z in direction:
            if 0 <= y + z[0] < h and 0 <= x + z[1] < w:
                if s[y + z[0]][x + z[1]] == '#':
                    p_sum += 1
        s[y][x] = p_sum

for y in range(h):
    for x in range(w):
        print(s[y][x], end='')
    print()

Submission status: Accepted

Solution code:
h,w = map(int,input().split())
a = ['x'*(w+2)]
for i in range(h):
  a.append('x'+input()+'x')
a.append('x'*(w+2))
for i in range(1,h+1):
  for j in range(1,w+1):
    count = 0
    if a[i][j] == '.':
      if a[i-1][j-1] == '#':
        count += 1
      if a[i-1][j] == '#':
        count += 1
      if a[i-1][j+1] == '#':
        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] == '#':
        count += 1
      a[i]=a[i].replace('.',str(count),1)
for i in a:
  if i == '':
    pass
  else:
    i = i.replace('x','')
    i = i.strip()
    print(i)

Submission status: Accepted

Solution code:
h,w = map(int,input().split())
s=[[x for x in input()] for i in range(h)]
for i in range(h):
	for j in range(w):
		if s[i][j]=='.':
			count=0
			for di in range(-1,2):
				for dj in range(-1,2):
					if not(0<=i+di<h and 0<=j+dj<w): pass
					elif s[i+di][j+dj]=="#":
						count += 1
			s[i][j]=str(count)
	print(''.join(s[i]))

Submission status: Accepted

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

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

dxy = [(-1,-1),(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1)]
for y in range(h):
    for x in range(w):
        if sL[y][x] == "#":
            continue
        count = 0
        for dx,dy in dxy:
            if x+dx < 0 or x+dx > w-1 or y+dy < 0 or y+dy > h-1: 
                continue
            if sL[y+dy][x+dx] == "#": 
                count += 1
        ans[y][x] = count
 
for row in ans:
    print(''.join(list(map(str,row))))

Submission status: Accepted

Solution code:
#a×bの数列
a, b = map(int, input().split())
fields=[]
for i in range(a):
  fields.append(list(input()))

#スニペット
#左上、上中、右上、左、（中を飛ばす）、右、左下、下中、右下
dx=[-1,0,1,-1,1,-1,0,1]
dy=[-1,-1,-1,0,0,1,1,1]

for i in range(a):
  for j in range(b):
    count = 0
    if fields[i][j]=="#":
      pass
    else:
      for k in range(8):
        if i+dx[k]>=0 and j+dy[k]>=0 and i+dx[k]<a and j+dy[k] < b :
          if fields[i+dx[k]][j+dy[k]]=="#":
            count+=1
      fields[i][j]=str(count)  
      
for i in range(a):
  print("".join(fields[i]))

Submission status: Accepted

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

for i in range(H):
    for j in range(W):
        cnt = 0
        if S[i][j] != "#":
            if i>0:
                if S[i-1][j] == "#":
                    cnt += 1
                if j>0 and S[i-1][j-1] == "#":
                    cnt += 1
                if j<W-1 and S[i-1][j+1] == "#":
                    cnt += 1
            if i<H-1:
                if S[i+1][j] == "#":
                    cnt += 1
                if j>0 and S[i+1][j-1] == "#":
                    cnt += 1
                if j<W-1 and S[i+1][j+1] == "#":
                    cnt += 1
            if j>0 and S[i][j-1] == "#":
                cnt += 1
            if j<W-1 and S[i][j+1] == "#":
                cnt += 1
            S[i][j] = str(cnt)
for i in range(H):
    print("".join(S[i]))

Submission status: Accepted

Solution code:
h, w = map(int,input().split())
arr = [input() for i in range(h)]
ans = []
for s in arr:
  ans.append(list(s))
dx = [1, 0, -1, 0, 1, -1, -1, 1]
dy = [0, 1, 0, -1, 1, 1, -1, -1]
for y in range(h):
  for x in range(w):
    if arr[y][x] == "#":
      continue
    num = 0
    for dx1,dy1 in zip(dx,dy):
      if x+dx1 < 0 or x+dx1 >= w:
        continue
      elif y+dy1 < 0 or y+dy1 >= h:
        continue
      if arr[y+dy1][x+dx1] == "#":
        num += 1
    ans[y][x] = num
for i in ans:
  print("".join(map(str,i)))

Submission status: Accepted

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

for i in range(h):
    for j in range(w):
        if s[i][j] == "0":
            for k in range(8):
                if 0 <= j+y[k] < w and 0 <= i+x[k] < h and s[i+x[k]][j+y[k]] == "#":
                    s[i][j] = str(int(s[i][j])+1)
                    
for i in range(h):
    print("".join(s[i]))

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
A = []
for i in range(H):
  A.append(input())
  
for i in range(H):
  for j in range(W):
    if A[i][j] == '#':
      print('#', end='')
    else:
      count = 0
      for k in range(max(0, i-1), min(i+1, H-1)+1):
        for l in range(max(0, j-1), min(j+1, W-1)+1):
          if A[k][l] == '#':
            count += 1
      print(count, end='')
  print()

Submission status: Accepted

Solution code:
def iread():
    return int(input())


def sread():
    return input()


def aread_int():
    tmp = input().split()
    ret = [int(i) for i in tmp]
    return ret


def aread_str():
    return input().split()


def check(arg):
    if arg == '#':
        return 1
    else:
        return 0

def format_print(matrix, colum, row):
    for i in range(colum):
        for j in range(row):
            print(matrix[i][j], end="")
        print("")

if __name__ == '__main__':
    h, w = map(int, input().split())
    matrix = []
    ans = []
    for _ in range(h):
        ans.append([0] * w)
        
    for _ in range(h):
        matrix.append(list(input()))

    for i in range(h):
        for j in range(w):
            if check(matrix[i][j]) > 0:
                ans[i][j] = '#'
            else:
                cnt = 0
                if i > 0 and i < h - 1:
                    cnt += check(matrix[i - 1][j])
                    cnt += check(matrix[i + 1][j])
                    if j > 0:
                        cnt += check(matrix[i - 1][j - 1])
                        cnt += check(matrix[i][j - 1])
                        cnt += check(matrix[i + 1][j - 1])
                    if j < w - 1:
                        cnt += check(matrix[i - 1][j + 1])
                        cnt += check(matrix[i][j + 1])
                        cnt += check(matrix[i + 1][j + 1])
                elif i > 0:
                    cnt += check(matrix[i - 1][j])
                    if j > 0:
                        cnt += check(matrix[i - 1][j - 1])
                        cnt += check(matrix[i][j - 1])
                    if j < w - 1:
                        cnt += check(matrix[i - 1][j + 1])
                        cnt += check(matrix[i][j + 1])
                elif i < h - 1:
                    cnt += check(matrix[i + 1][j])
                    if j > 0:
                        cnt += check(matrix[i][j - 1])
                        cnt += check(matrix[i + 1][j - 1])
                    if j < w - 1:
                        cnt += check(matrix[i][j + 1])
                        cnt += check(matrix[i + 1][j + 1])
                else:
                    if j > 0:
                        cnt += check(matrix[i][j - 1])
                    if j < w - 1:
                        cnt += check(matrix[i][j + 1])

                ans[i][j] = cnt
    format_print(ans, h, w)

Submission status: Accepted

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

if W ==1:
    if H ==2:
        if S[0]==".":
            A[0]=str(S[1].count("#"))
        if S[1]==".":
            A[1]=str(S[0].count("#"))
    else:
        for i in range(H):
            if S[i][0]==".":
                if i ==0:
                    A[0][0]=str(S[1][0].count("#"))
                elif i ==H-1:
                    A[H-1][0]=str(S[H-2][0].count("#")+S[H-1][0].count("#"))
                else:
                    A[i][0]=str(S[i-1][0].count("#")+S[i][0].count("#")+S[i+1][0].count("#"))
    for i in range(H):
        print("".join(A[i]))
    exit()

for i in range(W):
    for j in range(H):
        if S[j][i]==".":
            if i ==0 and j ==0:
                A[j][i] =str(S[0][0:2].count("#")+S[1][0:2].count("#"))
            elif i ==W-1 and j ==0:
                A[j][i] =str(S[0][W-2:W].count("#")+S[1][W-2:W].count("#"))
            elif i ==0 and j ==H-1:
                A[j][i] =str(S[H-2][0:2].count("#")+S[H-1][0:2].count("#"))
            elif i ==W-1 and j ==H-1:
                A[j][i] =str(S[H-2][W-2:W].count("#")+S[H-1][W-2:W].count("#"))
            elif i ==0:
                A[j][i] =str(S[j-1][0:2].count("#")+S[j][0:2].count("#")+S[j+1][0:2].count("#"))
            elif i ==W-1:
                A[j][i] =str(S[j-1][W-2:W].count("#")+S[j][W-2:W].count("#")+S[j+1][W-2:W].count("#"))
            elif j ==0:
                A[j][i] =str(S[0][i-1:i+2].count("#")+S[1][i-1:i+2].count("#"))
            elif j ==H-1:
                A[j][i] =str(S[H-2][i-1:i+2].count("#")+S[H-1][i-1:i+2].count("#"))
            else:
                A[j][i] =str(S[j-1][i-1:i+2].count("#")+S[j][i-1:i+2].count("#")+S[j+1][i-1:i+2].count("#"))
           
                
for i in range(H):
    print("".join(A[i]))

Submission status: Accepted

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

board = ['.'*(w+2)]

for i in range(h):
    line = input()
    board.append('.' + line + '.')
board.append('.'*(w+2))

new_board = []

for y in range(1,h+1):
    temp_text = ''

    for x in range(1, w+1):
        if board[y][x] == '#':
            temp_text = temp_text + '#'

        else:
            check_text = board[y-1][x-1:x+2] + board[y][x-1:x+2] + board[y+1][x-1:x+2]
            bomb_count = check_text.count('#')
            temp_text = temp_text + str(bomb_count)

    new_board.append(temp_text)

for text in new_board:
    print(text)

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
s=["."*(w+2)]
for i in range(h):
	s.append("."+input()+".")
s.append("."*(w+2))
for i in range(1,h+1):
	p=""
	for j in range(1,w+1):
		if s[i][j]==".":
			x=s[i-1][j-1:j+2]+s[i][j-1:j+2]+s[i+1][j-1:j+2]
			p+=str(x.count("#"))
		else:
			p+="#"
	print(p)

Submission status: Accepted

Solution code:
## グリッドに関する処理
# ABC075B_Minesweeper

## 考え方：
# A NG:pandasに入れて、df.ilocによる行×列のスライスでうまくやる -> pandasはimport不可
# B:np.arrayに入れて、うまいことやる  # PyPy3ではnumpyもimport不可。python3は、numpyはimport可。
# C:シンプルに、きれいに書き直す

## for test
# # 1
# height, width = 3, 5
# _s_list = ['.....', '.#.#.', '.....']

# # 2
# height, width = 3, 5
# _s_list = ['#####', '#####', '#####']

# 3
# height, width = 6, 6
# _s_list = ['#####.', '#.#.##', '####.#', '.#..#.', '#.##..', '#.#...']


## for submit
import numpy as np
height, width = map(int, input().split())
_s_list = [input() for i in range(height)]
s_list = [list(ss) for ss in _s_list]  # 列×行に1文字ずつ区切ってリストへ追加 -> 2次元配列化
s_arr  = np.array(s_list)
# print(s_list)  # debug
# print(s_arr)  # debug

ans_list = []
for _h in range(height):
    ans_row_str = ''
    for _w in range(width):
        # # 周囲1マスずつを取得
        # 条件式が真のときに返す値 if 条件式 else 条件式が偽のときに返す値
        h_s = 0 if _h <= 1 else _h-1
        h_e = _h + 2  # 範囲外アクセスはエラーにならない（負の値でなければOK）
        
        w_s = 0 if _w <= 1 else _w-1
        w_e = _w + 2
        
        # チェック対象の中心が#なら#, それ以外はcount_nonzeroで'#'をカウントした結果の数値を文字列として保存
        if s_arr[_h, _w] == '#':
            ans_row_str += '#'
        else:
            ans_row_str += str(np.count_nonzero(s_arr[h_s:h_e, w_s:w_e] == '#'))
    
    print(ans_row_str) # 1行を出力

Submission status: Accepted

Solution code:
def check(a,b):
  c = 0
  for i in range(max(0,a-1),min(h,a+2)):
    for j in range(max(0,b-1),min(w,b+2)):
      if s[i][j] == '#':
        c += 1
  return c
h,w = map(int,input().split())
s = [0] * h
for i in range(h):
  s[i] = list(input())
ns = [[0]*w for i in range(h)]
for a in range(h):
  for b in range(w):
    if s[a][b] != '#':
      ns[a][b] = str(check(a,b))
    else:
      ns[a][b] = '#'
for a in range(h):
  print(''.join(ns[a]))

Submission status: Accepted

Solution code:
## グリッドに関する処理
# ABC075B_Minesweeper

## 考え方：
# A NG:pandasに入れて、df.ilocによる行×列のスライスでうまくやる -> pandasはimport不可
# B:np.arrayに入れて、うまいことやる  # PyPy3ではnumpyもimport不可。python3は、numpyはimport可。

## for test
# # 1
# height, width = 3, 5
# _s_list = ['.....', '.#.#.', '.....']

# # 2
# height, width = 3, 5
# _s_list = ['#####', '#####', '#####']

# 3
# height, width = 6, 6
# _s_list = ['#####.', '#.#.##', '####.#', '.#..#.', '#.##..', '#.#...']


## for submit
import numpy as np
height, width = map(int, input().split())
_s_list = [input() for i in range(height)]
s_list = [list(ss) for ss in _s_list]  # 列×行に1文字ずつ区切ってリストへ追加 -> 2次元配列化
s_arr  = np.array(s_list)
# print(s_list)  # debug
# print(s_arr)  # debug

ans_list = []
for _h in range(height):
    for _w in range(width):
        # 周囲1マスずつを取得
        if _h <= 1:
            h_s = 0
        else:
            h_s = _h-1
        # h_e = _h + 2  # 一応、範囲外アクセスしないように修正
        if _h == height-1:
            h_e = _h+1
        else:
            h_e = _h+2
        
        if _w <= 1:
            w_s = 0
        else:
            w_s = _w - 1
        # w_e = _w + 2  # 一応、範囲外アクセスしないように修正
        if _w == width-1:
            w_e = _w+1
        else:
            w_e = _w+2

        # print(s_arr[h_s:h_e, w_s:w_e])  # debug
        # # np.count_nonzero()を使うとTrueの数、すなわち、条件を満たす要素の個数が得られる。
        # print(np.count_nonzero(s_arr[h_s:h_e, w_s:w_e] == '#'))

#         # 周囲1マスずつから、#の数を数えるための前処理
#         df_bool = (df.iloc[h_s:h_e, w_s:w_e] == '#')
#         # PythonでTrueは1、Falseは0とみなされるため、bool値のオブジェクトに対してsum()メソッドを呼べば条件を満たす要素の数が得られる。
#         # print(str(sum(df_bool.sum())))
        
        # チェック対象の中心が#なら#, それ以外はcount_nonzeroした結果の数値を文字列として保存
        if s_arr[_h, _w] == '#':
            ans_list.append('#')
        else:
            ans_list.append(str(np.count_nonzero(s_arr[h_s:h_e, w_s:w_e] == '#')))
        
# 結果を出力 width行を1区切りとして1行ずつ出力
ans_str = ''
for i in range(len(ans_list)):
    ans_str += ans_list[i]
    if (i+1) % width == 0:
        print(ans_str)
        ans_str = ''

Submission status: Accepted

Solution code:
h,w = map(int, input().split())
s = []
for i in range(h):
    t = input()
    t = '.' + t + '.'
    s.append(t)
t1 = ''
for i in range(w+2):
    t1 = t1 + '.'
res =['' for _ in range(h)]
s.append(t1)
s.insert(0,t1)
for i in range(1,h+1):
    for j in range(1,w+1):
        if s[i][j]=='#':
            res[i-1] = res[i-1]+'#'
        else:
            t2 = 0
            for k in range(-1,2):
                for l in range(-1,2):
                    if s[i+k][j+l]=='#':
                        t2 += 1
            res[i-1] = res[i-1]+str(t2)
for i in range(h):
    print(res[i])

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
grid = ["" for i in range(H)]
ans = [[0 for j in range(W)] for i in range(H)]

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

for i in range(H):
    grid[i] = input()
    
for i in range(H):
    for j in range(W):
        if grid[i][j] == "#":
            ans[i][j] = "#"
        else:
            count = 0
            for x, y in moves:
                cur_x = i + x
                cur_y = j + y
                if 0 <= cur_x and cur_x < H and 0 <= cur_y and cur_y < W and grid[cur_x][cur_y] == "#":
                    count += 1
            ans[i][j] = count
            
for i in range(H):
    print("".join(list(map(str, ans[i]))))

Submission status: Accepted

Solution code:
import numpy as np

#周りの'#'をカウントする関数
def countsherp(S_pad,i,j):
    count = 0
    for k in range(-1,2):
        for l in range(-1,2):
            if S_pad[i+k][j+l]=='#':
                count += 1
    return count

#入力
h, w = map(int,input().split()) 
S = np.array([list(input()) for i in range(h)])

#変数の初期化
w_pad = np.array([['p' for i in range(w)]])
h_pad = 'p'
S_pad = np.empty((0,w),int)

#padding処理(2次元配列の周りを'.'で囲む)
S_pad = np.append(S_pad,w_pad,axis=0)
S_pad = np.append(S_pad,S,axis=0)
S_pad = np.append(S_pad,w_pad,axis=0)
S_pad = np.insert(S_pad,0,h_pad,axis=1)
S_pad = np.insert(S_pad,S_pad.shape[1],h_pad,axis=1)

#'.'を数字に変換
for i in range(1,S_pad.shape[0]-1):
    for j in range(1,S_pad.shape[1]-1):
        count = 0
        if S_pad[i][j] == '.':
            S_pad[i][j] = countsherp(S_pad,i,j)

ans = S_pad[1:-1,1:-1]
for i in range(ans.shape[0]):
    print(''.join(ans[i]))

Submission status: Accepted

Solution code:
h,w = map(int,input().split())
ss = [input() for _ in [0]*h]
for i in range(h):
  ans = ''
  for j in range(w):
    if ss[i][j] == '#':
      ans += '#'
      continue
    n = 0
    if i > 0:
      n += ss[i-1][max(0,j-1):j+2].count('#')
    n += ss[i][max(0,j-1):j+2].count('#')
    if i != h-1:
      n += ss[i+1][max(0,j-1):j+2].count('#')
    ans += str(n)
  print(ans)

Submission status: Accepted

Solution code:
# ABC75, B - minesweeper
h, w = [int(el) for el in input().split(' ')]
S = [list(input()) for i in range(h)]

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



for i in range(h):
    for j in range(w):
        if S[i][j] == '.':
            count = 0
            for k in range(8):
                nx = j + dx[k]
                ny = i + dy[k]
                if (0 <= nx < w) and (0 <= ny < h):
                    if S[ny][nx] == '#':
                        count += 1
            S[i][j] = str(count)



[print(''.join(S[i])) for i in range(h)]

Submission status: Accepted

Solution code:
def solve():
    h, w = list(map(int, input().split()))
    field = [["."] * (w + 2)] + [["."] + list(input()) + ["."] for _ in range(h)] + [["."] * (w + 2)]
    # result = [[0] * (w + 2)] * (h + 2)

    for i in range(1, h + 1):
        for j in range(1, w + 1):
            if field[i][j] == ".":
                count = 0
                for dx in [-1, 0, 1]:
                    for dy in [-1, 0, 1]:
                        if field[i + dx][j + dy] == "#":
                            count += 1
                field[i][j] = str(count)

    for i in range(1, h + 1):
        print(''.join([str(e) for e in field[i][1:w + 1]]))


if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
H, W = [int(x) for x in input().split()]
cell = [['.' for x in range(W + 2)] for y in range(H + 2)]
for y in range(H):
    cell[y + 1][1:-1] = [c for c in input()]

def calc(row, col):
    bomb = 0
    for dx in [0, -1, 1]:
        for dy in [0, -1, 1]:
            if cell[row + dy][col + dx] == '#':
                bomb += 1
    return bomb

for row in range(H):
    for col in range(W):
        if cell[row + 1][col + 1] == '.':
            print(calc(row + 1, col + 1), end='')
        else:
            print('#', end='')
    print()

Submission status: Accepted

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

    SS = [[0 for i in range(W+2)] for j in range(H+2)]


    for i in range(H):
        for j in range(W):
            if S[i][j] == '#':
                # pass
                SS[i+1][j+1] = 1

    answer = S.copy()

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

    for i in range(H):
        for j in range(W):
            if answer[i][j] ==  '.':
                tmp = 0
                for k in range(8):
                    x = j + dx[k]
                    y = i + dy[k]
                    tmp += SS[y][x]
                answer[i][j] = str(tmp)

    for i in range(H):
        print("".join(answer[i]))

Submission status: Accepted

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

    SS = [[0 for i in range(W+2)] for j in range(H+2)]

    for i in range(H):
        for j in range(W):
            if S[i][j] == '#':
                # pass
                SS[i+1][j+1] = 1

    answer = S.copy()

    for i in range(H):
        for j in range(W):
            if answer[i][j] ==  '.':
                answer[i][j] = str(SS[i][j] + SS[i+1][j] + SS[i+2][j] + SS[i][j+1] + SS[i+2][j+1] + SS[i][j+2] + SS[i+1][j+2] + SS[i+2][j+2])

    for i in range(H):
        print("".join(answer[i]))

Submission status: Accepted

Solution code:
H, W = [int(hw) for hw in input().split()]
A = []
A.append("." * (W+2))
for h in range(H):
  A.append("." + input() + ".")
A.append("." * (W+2))

for h in range(1, H+1):
  for w in range(1, W+1):
    P = A[h][w]
    if P == ".":
      P_around = [A[h-1][w-1], A[h-1][w], A[h-1][w+1], \
                  A[h][w-1], A[h][w+1], \
                  A[h+1][w-1], A[h+1][w], A[h+1][w+1]]
      howmany_sharp = P_around.count("#")
      A[h] = A[h][:w] + str(howmany_sharp) + A[h][w+1:]

for h in range(1, H+1):
  print(A[h][1:W+1])

Submission status: Accepted

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

S = []
for _ in range(h):
  S.append(input())

for i in range(h):
  ss = ''
  for j in range(w):
    if S[i][j] == '#':
      ss += '#'
    else:
      counter = 0
      for k in [-1, 0, 1]:
        for l in [-1, 0, 1]:
          if 0 <= i+k <= h-1 and 0 <= j+l <= w-1 and S[i+k][j+l] == '#':
            counter += 1
      ss += str(counter)
  print(ss)

Submission status: Accepted

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

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

for i in range(h):
    for j in range(w):
        n = 0
        if li[i][j] == "#":
            continue

        for d in range(8):
            y = i + dy[d]
            x = j + dx[d]
            if x<0 or w<=x:
                continue
            if y<0 or h<=y:
                continue
            if li[y][x] == "#":
                n += 1
        li[i][j] = str(n)
for i in range(h):
    print("".join(li[i]))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
INF = float("inf")

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


def solve(H: int, W: int, S: "List[str]"):
    S = [list(s) for s in S]
    for i in range(H):
        for j in range(W):
            if S[i][j] == "#":
                continue
            counter = 0
            for dx, dy in zip(DX, DY):
                if i+dy < 0 or H <= i+dy:
                    continue
                if j+dx < 0 or W <= j+dx:
                    continue
                if S[i+dy][j+dx] == "#":
                    counter += 1
            S[i][j] = str(counter)

    print(*["".join(s) for s in S], sep="\n")
    return


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:
#!/usr/bin/env python3
import sys
INF = float("inf")


def solve(H: int, W: int, S: "List[str]"):
    S = [list(s) for s in S]
    for i in range(H):
        for j in range(W):
            if S[i][j] == "#":
                continue
            counter = 0
            for k in [-1, 0, 1]:
                for l in [-1, 0, 1]:
                    if k == 0 and l == 0:
                        continue
                    if i+k <= -1 or i+k >= H:
                        continue
                    if j+l <= -1 or j+l >= W:
                        continue
                    if S[i+k][j+l] == "#":
                        counter += 1
            S[i][j] = str(counter)

    print(*["".join(s) for s in S], sep="\n")
    return


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:
H, W = [int(x) for x in input().split()]

G = [" " * (W+2)] + [" " + input() + " " for _ in range(H)] + [" " * (W+2)]

for r in range(1, H+1):
    for c in range(1, W+1): 
        if G[r][c] != '.':
            print(G[r][c], end="")
        else:
            print(sum(1 for x in [
                G[r-1][c-1],
                G[r-1][c],
                G[r-1][c+1],
                G[r][c-1],
                G[r][c+1],
                G[r+1][c-1],
                G[r+1][c],
                G[r+1][c+1]] if x == '#'), end="")
    print()

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] == "#":
            continue
        cnt = 0
        for dx in [-1,0,1]:
            for dy in [-1,0,1]:
                if 0 <= i + dx < H and 0 <= j + dy < W:
                    if S[i+dx][j+dy] == "#":
                        cnt += 1
                else:
                    continue
        S[i][j] = str(cnt)

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

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
s = []
[s.append(list(input())) for x in range(h)]
for i in range(h):
    for j in range(w):
        if "." in s[i][j]:
            s[i][j] = 0
for i in range(h):
    for j in range(w):
        try:
            if "#" in s[i][j]:
                if i != 0 and j != 0:
                    s[i - 1][j - 1] += 1
        except IndexError:
            pass
        except TypeError:
            pass
        try:
            if "#" in s[i][j]:
                if i != 0:
                    s[i - 1][j] += 1
        except IndexError:
            pass
        except TypeError:
            pass
        try:
            if "#" in s[i][j]:
                if i != 0:
                    s[i - 1][j + 1] += 1
        except IndexError:
            pass
        except TypeError:
            pass
        try:
            if "#" in s[i][j]:
                if j != 0:
                    s[i][j - 1] += 1
        except IndexError:
            pass
        except TypeError:
            pass
        try:
            if "#" in s[i][j]:
                s[i][j + 1] += 1
        except IndexError:
            pass
        except TypeError:
            pass
        try:
            if "#" in s[i][j]:
                if j != 0:
                    s[i + 1][j - 1] += 1
        except IndexError:
            pass
        except TypeError:
            pass
        try:
            if "#" in s[i][j]:
                s[i + 1][j] += 1
        except IndexError:
            pass
        except TypeError:
            pass
        try:
            if "#" in s[i][j]:
                s[i + 1][j + 1] += 1
        except IndexError:
            pass
        except TypeError:
            pass
for i in s:
    print(''.join(map(str, i)))

Submission status: Accepted

Solution code:
def solve():
    board = read()
    result = think(board)
    write(result)


def read():
    h, w = read_int(2)
    board = []
    for y in range(h):
        board.append(read_line(w))
    return board


def read_int(n):
    return list(map(lambda x: int(x), read_line().split(' ')))[:n]


def read_line(n=0):
    if n == 0:
        return input().rstrip()
    else:
        return input().rstrip()[:n]


def think(board):
    # destructive method
    vacant_cell_symbol = '.'
    bomber_cell_symbol = '#'

    x_range, y_range = get_xy_range(board)

    new_board = [[0 for x in range(x_range)] for y in range(y_range)]

    for y in range(y_range):
        for x in range(x_range):
            if board[y][x] == bomber_cell_symbol:
                new_board[y][x] = bomber_cell_symbol
            else:
                cells = gather_cells_around(board, x, y)
                new_board[y][x] = cells.count(bomber_cell_symbol)
    return new_board


def get_xy_range(board):
    return len(board[0]), len(board)


def gather_cells_around(board, x, y):
    x_range, y_range = get_xy_range(board)
    offsets = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]
    cells = []
    for offset in offsets:
        if on_board(offset, x, y, x_range, y_range):
            cells.append(board[y + offset[1]][x + offset[0]])
    return cells


def on_board(offset, x, y, x_range, y_range):
    return 0 <= x + offset[0] < x_range and 0 <= y + offset[1] < y_range


def write(result):
    for line in result:
        print(''.join(list(map(lambda x: str(x), line))))

if __name__ == '__main__':
    solve()