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 itertools

H, W = map(int, input().split())
S = [input() for _ in range(H)]

SS = [[0 for _ in range(W)] for _ in range(H)]

for h in range(H):
	for w in range(W):
		if '#' in S[h][w] : SS[h][w] = -1

for h in range(H):
	for w in range(W):
		if SS[h][w] == -1:
			for y, x in itertools.product([-1, 0, 1], [-1, 0, 1]):
				if 0 <= h+y < H and 0 <= w+x < W:
					if SS[h+y][w+x] != -1 :
						SS[h+y][w+x] += 1

for h in range(H):
	for w in range(W):
		if SS[h][w] == -1:print('#', end="")
		else : print(SS[h][w], end="")
	print()

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
g=[input() for _ in range(h)]
a=[[0]*w for _ in range(h)]
for x in range(h):
  for y in range(w):
    if g[x][y]=='.': continue
    a[x][y]='#'
    for dx,dy in [(1,0),(0,1),(-1,0),(0,-1),(1,1),(-1,1),(-1,-1),(1,-1)]:
      nx,ny=x+dx,y+dy
      if 0<=nx<h and 0<=ny<w and g[nx][ny]=='.':
        a[nx][ny]+=1
for l in a:
  print(*l,sep='')

Submission status: Accepted

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

H,W = [int(i) for i in input().split()]
S = []
S.append('.'*(W+2))
for i in range(H):
    S.append('.'+input()+'.')
S.append(['.']*(W+2))

for y in range(1,H+1):
    for x in range(1,W+1):
        if S[y][x] == '#':
            print('#',end="")
        else:
            print(S[y-1][x-1:x+2].count('#')+S[y][x-1:x+2].count('#')+S[y+1][x-1:x+2].count('#'),end="")
    print("")

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().strip()

def main():
    H, W = map(int, input().split())
    S = ['.' * W] + [input() for _ in range(H)] + ['.' * W]
    if W == 1:
        for i in range(1, H + 1):
            if S[i] == '#':
                print('#')
                continue
            string = S[i - 1] + S[i + 1]
            cnt = string.count('#')
            print(str(cnt))
        return
    for i in range(1, H + 1):
        code = ""
        for j in range(W):
            if S[i][j] == '#':
                code += '#'
                continue
            if j == 0:
                string = S[i - 1][:2] + S[i][1] + S[i + 1][:2]
                cnt = string.count('#')
                code += str(cnt)
                continue
            if j == W - 1:
                string = S[i - 1][-2:] + S[i][-2] + S[i + 1][-2:]
                cnt = string.count('#')
                code += str(cnt)
                continue
            string = S[i - 1][j - 1:j + 2] + S[i][j - 1] + S[i][j + 1] + S[i + 1][j - 1:j + 2]
            cnt = string.count('#')
            code += str(cnt)
            continue
        print(code)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
S = [input() for _ in range(H)]
for i in range(H):
    S[i] = list(S[i])
    
if (H == 1) and (W == 1):
    if S[0][0] == '.':
        S[0] = '0'
elif (H == 1) and (W != 1):
    for col in range(W):
        if S[0][col] == '#':
            continue
        if col == 0:
            S[0][col] = str([S[0][col+1]].count('#'))
        elif col == W - 1:
            S[0][col] = str([S[0][col-1]].count('#'))
        else:
            S[0][col] = str([S[0][col-1], S[0][col+1]].count('#'))
elif (H != 1) and (W == 1):
    for row in range(H):
        if S[row][0] == '#':
            continue
        if row == 0:
            S[row][0] = str([S[row+1][0]].count('#'))
        elif row == H - 1:
            S[row][0] = str([S[row-1][0]].count('#'))
        else:
            S[row][0] = str([S[row-1][0], S[row+1][0]].count('#'))
else:
    for row in range(H):
        for col in range(W):
            if S[row][col] == '#':
                continue
            if row == 0:
                if col == 0:
                    S[row][col] = str([S[row][col+1], S[row+1][col], S[row+1][col+1]].count('#'))
                elif col == W - 1:
                    S[row][col] = str([S[row][col-1], S[row+1][col-1], S[row+1][col]].count('#'))
                else:
                    S[row][col] = str([S[row][col-1], S[row][col+1], S[row+1][col-1],
                               S[row+1][col], S[row+1][col+1]].count('#'))
            elif row == H - 1:
                if col == 0:
                    S[row][col] = str([S[row-1][col], S[row-1][col+1], S[row][col+1]].count('#'))
                elif col == W - 1:
                    S[row][col] = str([S[row-1][col-1], S[row-1][col], S[row][col-1]].count('#'))
                else:
                    S[row][col] = str([S[row-1][col-1], S[row-1][col], S[row-1][col+1],
                                   S[row][col-1], S[row][col+1]].count('#'))
            else:
                if col == 0:
                    S[row][col] = str([S[row-1][col], S[row-1][col+1],
                                   S[row][col+1],
                                   S[row+1][col], S[row+1][col+1]].count('#'))
                elif col == W - 1:
                    S[row][col] = str([S[row-1][col-1], S[row-1][col],
                                   S[row][col-1], 
                                   S[row+1][col-1], S[row+1][col]].count('#'))
                else:
                    S[row][col] = str([S[row-1][col-1], S[row-1][col], S[row-1][col+1],
                                   S[row][col-1], S[row][col+1],
                                   S[row+1][col-1], S[row+1][col], S[row+1][col+1]].count('#'))
for i in range(len(S)):
    print(''.join(S[i]))

Submission status: Accepted

Solution code:
from itertools import product

H, W = map(int, input().split())
S = [list(input()) for _ in range(H)]

for y, x in product(range(H), range(W)):
    if S[y][x] == "#":
        continue

    count = 0
    for i, j in product((-1, 0, 1), repeat=2):
        if not (0 <= y + i < H and 0 <= x + j < W):
            continue
        if S[y + i][x + j] == "#":
            count += 1
    S[y][x] = str(count)

print("\n".join("".join(r) for r in S))

Submission status: Accepted

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

def kazu(h,w):
    houkou = [[1,0],[1,-1],[0,-1],[-1,-1],[-1,0],[-1,1],[0,1],[1,1]]
    count = 0
    for ya in houkou:
        if 0 <= h+ya[0] < H and 0 <= w+ya[1] < W:
            if masu[h+ya[0]][w+ya[1]] == '#':
                count += 1

    return count

for w in range(W):
    for h in range(H):
        if masu[h][w]=='.':
            masu[h][w] = kazu(h,w)

for l in masu:print(*l,sep='')

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
s=[input() for _ in range(h)]
ans=[[] for _ in range(h)]
for i in range(h):
    for j in range(w):
        if s[i][j]==".":
            cnt=0
            for x,y in [(0,1),(1,0),(0,-1),(-1,0),(1,1),(1,-1),(-1,1),(-1,-1)]:
                if 0<=i+x<h and 0<=j+y<w:
                    if s[i+x][j+y]=="#":
                        cnt+=1
            ans[i].append(str(cnt))
        else:
            ans[i].append("#")
for i in range(h):
    print("".join(ans[i]))

Submission status: Accepted

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


for h in range(H):
    for w in range(W):
        x, y = w, h
        if S[y][x] == ".":
            c = 0
            for i in range(max(x-1, 0), min(x+2, W)):
                for j in range(max(y-1, 0), min(y+2, H)):
                    if S[j][i] == "#":
                        c += 1
            S[y][x] = str(c)

for h in range(H):
    print("".join(S[h]))

Submission status: Accepted

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

def update_count(i, j, count):
    count[i][j] = '#'
    start_i = 0 if i-1 < 0 else i-1
    end_i = H if i + 2 > H else i+2
    start_j = 0 if j-1 < 0 else j-1
    end_j = W if j + 2 > W else j+2
    for k in range(start_i, end_i):
        for l in range(start_j, end_j):
            if count[k][l] != '#':
                count[k][l] = str(1 + int(count[k][l]))
    return count

for i in range(H):
    S = input()
    for j in range(W):
        if S[j] == '#':
            count = update_count(i, j, count)

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

Submission status: Accepted

Solution code:
import copy
H,W=map(int,input().split())
List = []
for i in range (H):
  List.append(input())
resList = copy.deepcopy(List)

def bombCheck(x,y,ListX):  
  a = 0
  b = 0
  res = 0
  if ListX[x][y] == "#":
    return "#"
  for i in range(-1,2,1):
    a = x+i
    if 0<= a < H:
      for j in range(-1,2,1):
        b = y+j
        if 0<= b < W:
          if i == 0 and j ==0:
            pass
          else:
            if List[a][b] == "#":
              res +=1
  return str(res)

for i in range(H):
  resList[i] =""
  for j in range(W):
    resList[i] += bombCheck(i,j,List)
for i in resList:
  print(i)

Submission status: Accepted

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

if h == 1 and w == 1:
    if s[0][0] == "#":
        print("#")
    else:
        print(0)

elif h == 1:
    for j in range(w):
        if s[0][j] == ".":
            ans[0][j] = s[0][max(0, j - 1):min(w + 1, j + 2)].count("#")
        else:
            ans[0][j] = "#"

elif w == 1:
    for i in range(h):
        if i == 0:
            if s[i][0] == ".":
                ans[i][0] = s[i + 1][0].count("#")
            else:
                ans[i][0] = "#"
        elif i == h - 1:
            if s[i][0] == ".":
                ans[i][0] = s[i - 1][0].count("#")
            else:
                ans[i][0] = "#"
        else:
            if s[i][0] == ".":
                ans[i][0] = s[i - 1][0].count("#") + s[i+1][0].count("#")
            else:
                ans[i][0] = "#"

else:
    for i in range(h):
        for j in range(w):
            if i == 0:
                if s[i][j] == ".":
                    ans[i][j] = s[i][max(0, j - 1):min(w + 1, j + 2)].count("#") + s[i + 1][
                                                                                   max(0, j - 1):min(w + 1, j + 2)].count(
                        "#")
                else:
                    ans[i][j] = "#"
            elif i == h-1:
                if s[i][j] == ".":
                    ans[i][j] = s[i - 1][max(0, j - 1):min(w + 1, j + 2)].count("#") + s[i][max(0, j - 1):min(w + 1,
                                                                                                              j + 2)].count(
                        "#")
                else:
                    ans[i][j] = "#"
            else:
                if s[i][j] == ".":
                    ans[i][j] = s[i - 1][max(0, j - 1):min(w + 1, j + 2)].count("#") + s[i][max(0, j - 1):min(w + 1,
                                                                                                              j + 2)].count(
                        "#") + s[i + 1][max(0, j - 1):min(w + 1, j + 2)].count("#")
                else:
                    ans[i][j] = "#"

[print(*k,sep="") for k in ans]

Submission status: Accepted

Solution code:
import sys
def MI(): return map(int,sys.stdin.readline().rstrip().split())
def LS2(): return list(sys.stdin.readline().rstrip())  #空白なし

H,W = MI()
S = [['.']*(W+2)]
for i in range(H):
    S.append(['.'] + LS2() + ['.'])
S.append(['.']*(W+2))

ANS = [[] for i in range(H+1)]
for i in range(1,H+1):
    for j in range(1,W+1):
        if S[i][j] == '#':
            ANS[i].append('#')
        else:
            ANS[i].append(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(1,H+1):
    print(''.join(ANS[i]))

Submission status: Accepted

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

wall = ["." * (w + 2)]
s = wall + ["." + input() + "." for _ in range(h)] + wall

for i in range(1, h + 1):
    for j in range(1, w + 1):
        if s[i][j] == ".":
            t = s[i-1][j-1:j+2] + s[i][j-1:j+2] + s[i+1][j-1:j+2]
            s[i] = s[i][:j] + str(t.count("#")) + s[i][j+1:]
    else:
        print(s[i][1:-1])

Submission status: Accepted

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

t = [[0 for _ in range(w)] for _ in range(h)]
for i in range(h):
    for j in range(w):
        if s[i][j] == ".":
            bombs = 0
            for k in range(i - 1, i + 2):
                for l in range(j - 1, j + 2):
                    if 0 <= k < h and 0 <= l < w:
                        if s[k][l] == "#":
                            bombs += 1
            else:
                t[i][j] = str(bombs)
        else:
            t[i][j] = "#"
else:
    for i in range(h):
        print("".join(t[i]))

Submission status: Accepted

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

for _ in range(h):
    board.append(input())

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

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

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

            if (ni < 0 or ni >= h) or (nj < 0 or nj >= w):
                continue
            if board[ni][nj] == "#":
                cnt += 1

        temp_board = list(board[i])
        temp_board[j] = str(cnt)
        board[i] = "".join(temp_board)

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

Submission status: Accepted

Solution code:
import copy
H, W = list(map(int, input().split()))
tb = []
for h in range(H+2):
    line = []
    if h == 0 or h == H+2-1:
        for w in range(W+2):
            line.append(0)
    else:
        line = list("." + input() + ".")
        for w in range(W+2):
            if line[w] == ".":
                line[w] = 0
    tb.append(line)
#def xxx(): [print("".join(list(map(str,line)))) for line in tb];print()
#xxx()


for i in range(1,H+1):
    for j in range(1,W+1):
        if tb[i][j] != "#":
            if tb[i-1][j] == "#": tb[i][j] += 1
            if tb[i+1][j] == "#": tb[i][j] += 1
            if tb[i][j-1] == "#": tb[i][j] += 1
            if tb[i][j+1] == "#": tb[i][j] += 1
            if tb[i-1][j-1] == "#": tb[i][j] += 1
            if tb[i-1][j+1] == "#": tb[i][j] += 1
            if tb[i+1][j-1] == "#": tb[i][j] += 1
            if tb[i+1][j+1] == "#": tb[i][j] += 1

#xxx()
[print("".join(list(map(str,line)))[1:-1]) for i,line in enumerate(tb) if 0 < i < H+2-1];print()

Submission status: Accepted

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

#左上から時計回り
dy = [-1, -1, -1, 0, 1, 1, 1, 0]
dx = [-1, 0, 1, 1, 1, 0, -1, -1]

for i in range(h):
    for j in range(w):
        if s[i][j] == "#": continue
        cnt = 0
        for k in range(8):
            x = j + dx[k]
            y = i + dy[k]
            if x < 0 or y < 0 or w <= x or h <= y: continue
            if s[y][x] == "#":
                cnt += 1
        s[i][j] = str(cnt)
print(*map("".join, s), sep = "\n")

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
from itertools import chain
from copy import deepcopy
def main():
    h, w = map(int, input().split())
    # '#'を1に、'.'を-1に置き換える。
    # 上下左右にダミーのマスとして0を置く。
    hw = []
    hw.append([0] * (w + 2))
    for _ in range(h):
        row = list(input())
        row2 = [-1 if i == '#' else 0 for i in row]
        row3 = list(chain([0], row2, [0]))
        hw.append(row3)
    hw.append([0] * (w + 2))
    hw2 = deepcopy(hw)
    for i1 in range(1, h + 1):
        for i2 in range(1, w + 1):
            if hw[i1][i2] == 0:
                bombs = sum(hw[i1 - 1][i2-1:i2+2])
                bombs += sum(hw[i1][i2 - 1:i2 + 2])
                bombs += sum(hw[i1 + 1][i2 - 1:i2 + 2])
                hw2[i1][i2] = - bombs
    for j1 in range(1, h + 1):
        row4 = hw2[j1][1:w+1]
        row5 = ['#' if i == -1 else str(i) for i in row4]
        print("".join(row5))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    import sys

    def input(): return sys.stdin.readline().rstrip()
    
    h, w = map(int, input().split())
    g = [[] for _ in range(h)]
    di = [-1, 0, 1, 0, 1, 1, -1, -1]
    dj = [0, 1, 0, -1, 1, -1, -1, 1]

    for i in range(h):
        g[i] = list(input())
        
    for i in range(h):
        for j in range(w):
            if g[i][j] == '#':
                continue
            
            cnt = 0
            for k in range(8):
                ni = i + di[k]
                nj = j + dj[k]
                if ni < 0 or ni >= h or nj < 0 or nj >= w:
                    continue
                if g[ni][nj] == '#':
                    cnt += 1
            g[i][j] = str(cnt)
    
    for i in g:
        print(''.join(i))

            



if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
h, w = map(int, input().split())
s = [[0 if i == "." else -9 for i in input()] for _ in range(h)]
d = ((1, 0), (1, 1), (1, -1), (-1, 0), (-1, 1), (-1, -1), (0, 1), (0, -1))
for i in range(h):
    for j in range(w):
        if s[i][j] < 0:
            for x, y in d:
                if 0 <= i + x < h and 0 <= j + y < w:
                    s[i + x][j + y] += 1
for i in s:
    print(*["#" if j < 0 else j for j in i], sep="")

Submission status: Accepted

Solution code:
h, w = map(int, input().split(" "))
s = []
for i in range(h):
    s.append(str(input()))
d = [(1, 0), (0, 1), (-1, 0), (0, -1), (1, 1), (-1, 1), (1, -1), (-1, -1)]
ss = ["" for i in range(h)]
for i in range(w):
    for j in range(h):
        if s[j][i] == "#":
            ss[j] += "#"
            continue
        cnt = 0
        for dx, dy in d:
            if 0 <= i + dx < w and 0 <= j + dy < h:
                if s[j + dy][i + dx] == "#":
                    cnt += 1
        ss[j] = ss[j] + str(cnt)

for i in ss:
    print(i)

Submission status: Accepted

Solution code:
if __name__ == "__main__":
    h,w = map(int,input().split())
    s = []
    s.append([0]*(w+2))

    for i in range(h):
        q = [0]
        q.extend(list(input()))
        q.append(0)
        s.append(q)
    s.append([0]*(w+2))

    for p in range(h):
        for q in range(w):
            if s[p+1][q+1] == "#":
                print("#",end = "")
            else:
                aro = [s[p][q],s[p+1][q],s[p+2][q],s[p][q+1],s[p+2][q+1],s[p][q+2],s[p+1][q+2],s[p+2][q+2]]
                print(aro.count("#"),end = "")
        print("")

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
d = [(1, 0), (0, 1), (-1, 0), (0, -1), (1, 1), (-1, 1), (1, -1), (-1, -1)]
G = [list(input()) for _ in range(H)]
ans = [[""] * W for _ in range(H)]
for i in range(H):
    for j in range(W):
        if G[i][j] == '#':
            ans[i][j] = '#'
            continue
        cnt = 0
        for dx, dy in d:
            ni = i + dx
            nj = j + dy
            if ni < 0 or H <= ni or nj < 0 or W <= nj:
                continue
            if G[ni][nj] == '#':
                cnt += 1
        ans[i][j] = str(cnt)
for a in ans:
    print(''.join(a))

Submission status: Accepted

Solution code:
s = input().split()
h = int(s[0])
w = int(s[1])

mine = [[0 for j in range(w)] for i in range(h)]


# 入力
for j in range(h):
    p = input()
    q = list(p)
    for i in range(w):
        mine[j][i] = str(q[i])

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 mine[i][j] == '#':
            continue

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

            if ni < 0 or h <= ni:
                continue
            if nj < 0 or w <= nj:
                continue
            if mine[ni][nj] == '#':
                num += 1
        
        
        mine[i][j] = str(num)

for i in range(h):
    for j in range(w):
        print(mine[i][j],end='')
    print('')

print('')

Submission status: Accepted

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


def search(th, tw):
    t = 0
    for i in range(-1, 2):
        for j in range(-1, 2):
            if i == j == 0:
                continue
            if not 0 <= th+i < h:
                continue
            if not 0 <= tw+j < w:
                continue
            if ls[th+i][tw+j] == "#":
                t += 1
    return t


ans = ""
for i in range(h):
    for j in range(w):
        if ls[i][j] == "#":
            ans += "#"
        else:
            ans += str(search(i, j))
    ans += "\n"

print(ans)

Submission status: Accepted

Solution code:
from collections import deque
H, W = map(int,input().split())
sl = []
for _ in range(H):
    sl.append(list(input()))



for i in range(H):
    for j in range(W):
        if sl[i][j] == '#':
            continue

        cnt = 0
        directions = [[1, 0], [0, 1], [-1, 0], [0, -1], [1, 1], [-1, -1], [1, -1], [-1, 1]]
        for d in directions:
            y,x = i+d[0],j+d[1]
            if i+d[0] >= H:
                continue
            if i+d[0] < 0:
                continue
            if j+d[1] >= W:
                continue
            if j + d[1] < 0:
                continue
            if sl[y][x] == '#':
               cnt += 1
        sl[i][j] = str(cnt)

for v in sl:
    print(''.join(v))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(4100000)
import math
INF = 10**9

def main():
    h,w = map(int, input().split())
    S = [input() for _ in range(h)]
    ans = [[0]*(w+2) for _ in range(h)]
    ans.insert(0, [0]*(w+2))
    ans.append([0]*(w+2))

    for i in range(h):
        for j in range(w):
            if S[i][j] == '#':
                for k in [-1, 0, 1]:
                    for l in [-1, 0, 1]:
                        if k == l == 0:
                            ans[i+1][j+1] = '#'
                        if ans[i+k+1][j+l+1] != '#':
                            ans[i+k+1][j+l+1] += 1
    for i in range(1,h+1):
        tmp = ''
        for j in range(1,w+1):
            tmp += str(ans[i][j])
        print(tmp)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

for i in range(h):
    for j in range(w):
        if field[i][j] == '.':
            count = 0
            for s in range(max(0,i-1), min(h,i+2)):
                for t in range(max(0,j-1), min(w,j+2)):
                    if field[s][t]=='#':
                        count += 1
            field[i][j] = count
        print(field[i][j], end='')
    print()

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
S = [input() for _ in range(H)]
 
ans = [[0]*W for _ in range(H)]
 
for i in range(H):
    for j in range(W):
        if S[i][j] == "#":
            ans[i][j] += 11

#入力が1列の場合
if W == 1:
    for i in range(H-1):
        if ans[i+1][0] > 10:
            ans[i][0] += 1
    for i in range(1, H):
        if ans[i-1][0] > 10:
            ans[i][0] += 1

    for i in range(H):
        if ans[i][0] > 10:
            ans[i][0] = "#"
        ans[i] = map(str, ans[i])
        ans[i] = "".join(ans[i])

    for a in ans:
        print(a)
    exit()
 
#横方向の確認
for i in range(H):
    for j in range(W - 1):
        if ans[i][j+1] > 10:
            ans[i][j] += 1
    for j in range(1, W):
        if ans[i][j-1] > 10:
            ans[i][j] += 1
 
#縦方向の確認
for j in range(1, W-1):
    for i in range(H-1):
        if ans[i+1][j-1] > 10:
            ans[i][j] += 1
        if ans[i+1][j] > 10:
            ans[i][j] += 1
        if ans[i+1][j+1] > 10:
            ans[i][j] += 1
 
    for i in range(1, H):
        if ans[i-1][j-1] > 10:
            ans[i][j] += 1
        if ans[i-1][j] > 10:
            ans[i][j] += 1
        if ans[i-1][j+1] > 10:
            ans[i][j] += 1
 
#j = 0
for i in range(H-1):
    if ans[i+1][0] > 10:
        ans[i][0] += 1
    if ans[i+1][1] > 10:
        ans[i][0] += 1
for i in range(1, H):
    if ans[i-1][0] > 10:
        ans[i][0] += 1
    if ans[i-1][1] > 10:
        ans[i][0] += 1
 
#j = W-1
for i in range(H-1):
    if ans[i+1][W-1] > 10:
        ans[i][W-1] += 1
    if ans[i+1][W-2] > 10:
        ans[i][W-1] += 1
for i in range(1, H):
    if ans[i-1][W-1] > 10:
        ans[i][W-1] += 1
    if ans[i-1][W-2] > 10:
        ans[i][W-1] += 1
 
for i in range(H):
    for j in range(W):
        if ans[i][j] > 10:
            ans[i][j] = "#"
    ans[i] = map(str, ans[i])
    ans[i] = "".join(ans[i])
 
for a in ans:
    print(a)

Submission status: Accepted

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

around=[[0,1],[0,-1],[1,0],[-1,0],[1,1],[1,-1],[-1,1],[-1,-1]]

for i in range(h):
  for j in range(w):
    x,y=i,j
    if s[x][y]==".":
      cnt=0
      for a in around:
        if (x+a[0]<0 or x+a[0]>h-1) or (y+a[1]<0 or y+a[1]>w-1):
          continue
        if s[x+a[0]][y+a[1]]=="#":
          cnt+=1
      ans[x][y]=str(cnt)
    

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

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
h, w = map(int, input().split())
s = [[c for c in l.strip()] for l in sys.stdin]



for i in range(h):
    line = ""
    for j in range(w):
        
        cnt = 0

        if s[i][j] == "#":
            line += "#"
        else:
            #上の行3マス
            if i != 0:
                if j != 0:
                    if s[i - 1][j - 1] == "#":
                        cnt += 1
                if s[i - 1][j] == "#":
                    cnt += 1
                if j != w - 1:
                    if s[i - 1][j + 1] == "#":
                        cnt += 1

            #同じ行2マス
            if j != 0:
                if s[i][j - 1] == "#":
                    cnt += 1
            if j != w - 1:
                if s[i][j + 1] == "#":
                    cnt += 1

            #下の行3マス
            if i != h - 1:
                if j != 0:
                    if s[i + 1][j - 1] == "#":
                        cnt += 1
                if s[i + 1][j] == "#":
                    cnt += 1
                if j != w - 1:
                    if s[i + 1][j + 1] == "#":
                        cnt += 1
            line += str(cnt)
    print(line)

Submission status: Accepted

Solution code:
import sys

def I(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def main():
    h, w = MI()
    s = [input() for _ in range(h)]
    table = [[0]*(w+2) for _ in range(h+2)]
    for i in range(1, h+1):
        for j in range(1, w+1):
            table[i][j] = s[i-1][j-1]
    for i in range(1, h+1):
        for j in range(1, w+1):
            if table[i][j] == '#':
                print('#', end='')
                continue
            cnt = 0
            for k in range(i-1, i+2):
                for l in range(j-1, j+2):
                    if table[k][l] == '#':
                        cnt += 1
            print(cnt, end='')
        print()

if __name__ == '__main__':
    main()

Submission status: Accepted

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

T=[]

for y in range(H+2):
    H=""
    for x in range(W+2):
        if S[y][x]==".":
            K=0
            for b in range(-1,2):
                for a in range(-1,2):
                    K+=(S[y+b][x+a]=="#")
            H+=str(K)
        else:
            H+=S[y][x]
    T.append(H)

print("\n".join(map(lambda x:x[1:-1],T[1:-1])))

Submission status: Accepted

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

M = [[0] * (W + 2) for _ in range(H + 2)]

for i in range(H):
    for j in range(W):
        if S[i][j] == '#':
            for k in range(3):
                for l in range(3):
                    if k == l == 1:
                        M[i + k][j + l] = '#'
                    else:
                        if M[i + k][j + l] != '#':
                            M[i + k][j + l] += 1

for i in range(1, H + 1):
    for j in range(1, W + 1):
        print(M[i][j], end='')
    print('')

Submission status: Accepted

Solution code:
import sys, os, math, bisect, itertools, collections, heapq, queue
# from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall
from decimal import Decimal
from collections import defaultdict, deque

sys.setrecursionlimit(10000000)

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: (x * y) // math.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    H, W = il()
    S = [iss() for _ in range(H)]

    move = [[-1, 1], [0, 1], [1, 1], [-1, 0], [1, 0], [-1, -1], [0, -1], [1, -1]]
    ret = []
    for _ in range(H):
        ret.append([0] * W)

    for h in range(H):
        for w in range(W):
            if S[h][w] == '.':
                continue
            else:
                ret[h][w] = '#'
                for mw, mh in move:
                    if w + mw >= W or h + mh >= H: continue
                    if w + mw < 0 or h + mh < 0: continue
                    if ret[h + mh][w + mw] != '#': ret[h + mh][w + mw] += 1

    for r in ret:
        print(*r, sep='')


if __name__ == '__main__':
    main()