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:
def B_Minesweeper(H, W, S):
    # 書き換え後のフィールド
    board = S.copy()
    # ある点の右、下、左、上、右下、左下、左上、右上
    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 board[i][j] == '#':
                continue

            num = 0  # 周囲8マスの#の数
            for k in range(8):
                y = i + dy[k]
                x = j + dx[k]

                if x < 0 or W <= x:
                    continue
                if y < 0 or H <= y:
                    continue
                if board[y][x] == '#':
                    num += 1
            board[i] = board[i][:j] + chr(ord('0') + num) + board[i][j+1:]

    for s in board:
        print(''.join(s))
    return None
  
H,W = [int(i) for i in input().split()]
S = [input() for _ in range(H)]
B_Minesweeper(H, W, S)

Submission status: Accepted

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

H, W = map(int, raw_input().split())

S = []
for i in range(0, H):
	S.append(raw_input())

ans = [["" for i in range(W)] for j in range(H)]

dx = (1, 0, -1,  0, 1, -1, -1,  1)
dy = (0, 1,  0, -1, 1,  1, -1, -1)

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

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

			if ni < 0 or H <= ni: continue
			if nj < 0 or W <= nj: continue
			if S[ni][nj] == "#": count+=1

		ans[i][j] = str(count)


for i in range(0, H):
	for j in range(0, W):
		sys.stdout.write(ans[i][j])
	print

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
mass = []
for _ in range(H):
    mass.append(list(input()))
for i in range(H):
    for j in range(W):
        counter = 0
        if mass[i][j] == "#":
            print("#", end="")
        else:
            for k in range(-1, 2, 1):
                for l in range(-1, 2, 1):
                    if k == 0 and l == 0:
                        continue
                    if i + k < 0 or i + k >= H or j + l < 0 or j + l >= W:
                        continue
                    if mass[i + k][j + l] == "#":
                        counter += 1
            print(counter, end="")
    print()

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
S=[]
for i in range(H):
     S.append(input())
for i in range(H):
    for j in range(W):
        if S[i][j] == "#":
            print("#",end="")
        else:
            rec = 0
            for d in [(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1)]:
                nx,ny = i+d[0],j+d[1]
                if 0 <= nx < H and 0 <= ny < W and S[nx][ny] == "#":
                    rec += 1
            print(rec,end="")
            
    print()

Submission status: Accepted

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

H, W = map(int, raw_input().split())

S = []
for i in range(0, H):
	S.append(raw_input())

ans = [["" for i in range(W)] for j in range(H)]

for i in range(0, H):
	for j in range(0, W):
		if S[i][j] == "#":
			ans[i][j] = "#"
		else:
			count = 0

			# i-1
			if i-1 >= 0:
				if j-1 >= 0:
					if S[i-1][j-1] == "#":
						count+=1
				if S[i-1][j] == "#":
					count+=1
				if j+1 < W:
					if S[i-1][j+1] == "#":
						count+=1
			# i
			if j-1 >= 0:
				if S[i][j-1] == "#":
					count+=1
			if j+1 < W:
				if S[i][j+1] == "#":
					count+=1
			# i+1
			if i+1 < H:
				if j-1 >= 0:
					if S[i+1][j-1] == "#":
						count+=1
				if S[i+1][j] == "#":
					count+=1
				if j+1 < W:
					if S[i+1][j+1] == "#":
						count+=1

			ans[i][j] = str(count)

for i in range(0, H):
	for j in range(0, W):
		sys.stdout.write(ans[i][j])
	print

Submission status: Accepted

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

c = [[0] * (W+2) for i in range(H+2)]
for i in range(H):
    for j in range(W):
        if b[i][j] == "#":
            c[i][j] += 1
            c[i+1][j] += 1
            c[i+2][j] += 1
            c[i][j+1] += 1
            # c[i+1][j+1] += 1
            c[i+2][j+1] += 1
            c[i][j+2] += 1
            c[i+1][j+2] += 1
            c[i+2][j+2] += 1
d = [""] * H
for i in range(H):
    for j in range(W):
        if b[i][j] == ".":
            d[i] += str(c[i+1][j+1])
        else: d[i] +="#"

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

Submission status: Accepted

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

offset_h = (-1,-1,-1,0,0,1,1,1)
offset_w = (-1,0,1,-1,1,-1,0,1)
for h in range(H):
  for w in range(W):
    if S[h][w] == "#":
      print("#", end="")
    else:
      bomb = 0
      for i,j in zip(offset_h, offset_w):
        if h+i >= 0 and h+i < H and w+j >=0 and w+j < W and S[h+i][w+j]=="#":
          bomb += 1
            
      print(bomb, end="")
     
  print("")

Submission status: Accepted

Solution code:
def graph_apd(idx,jdx):
    
    li = ([1,0],[-1,0],[0,-1],[0,1],[1,1],[-1,-1],[1,-1],[-1,1])
    
    for i in li:
        if ((idx+i[0])==-1):continue
        if ((jdx+i[1])==-1):continue
        try:
            if graph2[idx+i[0]][jdx+i[1]]:
                
                if graph2[idx+i[0]][jdx+i[1]] != "#":
                    graph2[idx+i[0]][jdx+i[1]] += 1
            else:
                graph2[idx+i[0]][jdx+i[1]] = 1
        except IndexError:
            pass
        

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

graph1 = [[]for i in range(h)]

for i in range(h):
    x = input().replace("\r","")
    graph1[i].append(x)
          


graph2 = [ [None for i in range(w)] for j in range(h)]

for idx,i in enumerate(graph1):
    for jdx in range(len(graph1[idx][0])):
        if graph1[idx][0][jdx] == "#":
            graph2[idx][jdx] = "#"
            graph_apd(idx,jdx)
    
ret = [[] for i in range(h)]
        
for idx,i in enumerate(graph2):
    for jdx,j in enumerate(graph2[idx]):
        if graph2[idx][jdx]:
            graph2[idx][jdx] = str(graph2[idx][jdx])
        else:
            graph2[idx][jdx] = "0"
    ret[idx] = "".join(graph2[idx])
    print(ret[idx])

Submission status: Accepted

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

import sys


def main():
    s, w = [int(x) for x in sys.stdin.readline().rstrip().split(" ")]
    data = []
    for line in sys.stdin:
        data.append(list(line.rstrip()))

    for i in range(s):
        for j in range(w):
            if data[i][j] == "#":
                continue
            count = 0
            for k in range(max(i - 1, 0), min(i + 2, s)):
                for l in range(max(j - 1, 0), min(j + 2, w)):
                    if data[k][l] == "#":
                        count += 1
            data[i][j] = str(count)

    for line_arr in data:
        print("".join(line_arr))

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:

x = list(map(int, input().split()))
k = [list(map(str, input())) for i in range(x[0])]

def check(i,j,k):
    if k[i][j]=='#':
        return '#'
    count=0
    if len(k)==1:
        if len(k[0])==1:
            if k[0][0]=='#':
                return '#'
            return 0
        if len(k[0])!=1:
            if j==0:
                if k[0][1]=='#':
                    count+=1
                return count
            if j==len(k[0])-1:
                if k[0][len(k[0])-2]=='#':
                    count+=1
                return count
            for jj in range(-1,2):
                if jj==0:
                    continue
                if k[0][j+jj]=='#':
                    count+=1
            return count

    if len(k[0])==1:
        if i==0:
            if k[1][0]=='#':
                count+=1
            return count
        if i==len(k)-1:
            if k[len(k)-2][0]=='#':
                count+=1
            return count
        for ii in range(-1,2):
            if ii==0:
                continue
            if k[i+ii][0]=='#':
                count+=1
        return count           


    if i==0 and j==0:
        for ii in range(0,2):
            for jj in range(0,2):
                if ii==0 and jj==0:
                    continue
                if k[i+ii][j+jj]=='#':
                    count+=1
        return count
    if i==0 and j==len(k[0])-1:
        for ii in range(0,2):
            for jj in range(-1,1):
                if ii==0 and jj==0:
                    continue
                if k[i+ii][j+jj]=='#':
                    count+=1
        return count    

    if i==len(k)-1 and j==0:
        for ii in range(-1,1):
            for jj in range(0,2):
                if ii==0 and jj==0:
                    continue
                if k[i+ii][j+jj]=='#':
                    count+=1
        return count 
    if i==len(k)-1 and j==len(k[0])-1:
        for ii in range(-1,1):
            for jj in range(-1,1):
                if ii==0 and jj==0:
                    continue
                if k[i+ii][j+jj]=='#':
                    count+=1
        return count
    if i==0:
        for ii in range(0,2):
            for jj in range(-1,2):
                if ii==0 and jj==0:
                    continue
                if k[i+ii][j+jj]=='#':
                    count+=1
        return count

    if i==len(k)-1:
        for ii in range(-1,1):
            for jj in range(-1,2):
                if ii==0 and jj==0:
                    continue
                if k[i+ii][j+jj]=='#':
                    count+=1
        return count

    if j==0:
        for ii in range(-1,2):
            for jj in range(0,2):
                if ii==0 and jj==0:
                    continue
                if k[i+ii][j+jj]=='#':
                    count+=1 
        return count

    if j==len(k[0])-1:
        for ii in range(-1,2):
            for jj in range(-1,1):
                if ii==0 and jj==0:
                    continue
                if k[i+ii][j+jj]=='#':
                    count+=1
        return count
       
    for ii in range(-1,2):
        for jj in range(-1,2):
            if ii==0 and jj==0:
                continue
            if k[i+ii][j+jj]=='#':
                count+=1
    return count

res=[]
for ik in range(len(k)):
    for jk in range(len(k[0])):
        res.append(check(ik,jk,k))  

for i in range(x[0]):
    sta=0+x[1]*i
    fin=x[1]+x[1]*i
    while sta<fin:
        print(res[sta],end='')
        sta +=1
    print('')
quit()

Submission status: Accepted

Solution code:
def main():
    b = []
    line = input().split(" ")
    H = int(line[0])
    W = int(line[1])
    for l in range(H):
        b.append(input())

    result = []
    for i, line in enumerate(b):
        result_row = ""
        for j, c in enumerate(line):
            if c == ".":
                n = count(i, j, b, H, W)
                result_row += str(n)
            else:
                result_row += b[i][j]
        result.append(result_row)

    for l in result:
        print(l)


def count(row, column, board, H, W):
    n = 0
    rs, re = judge_row(row, H)
    cs, ce = judge_col(column, W)
    for r in range(rs, re):
        for c in range(cs, ce):
            if board[r][c] == "#":
                n += 1
    return n


def judge_row(row, H):
    if H == 1:
        return 0, 1
    elif row == 0:
        return row, row+1+1 
    elif row == H-1:
        return row-1, row+1
    else:
        return row-1, row+1+1


def judge_col(col, W):
    if W == 1:
        return 0, 1
    elif col == 0:
        return col, col+1+1 
    elif col == W-1:
        return col-1, col+1
    else:
        return col-1, col+1+1


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
H,W=list(map(int,raw_input().split()))
a = []
for i in range(H):
    a.append(list(raw_input()))
#print a

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


for i in range(H):
	maped_num = map(str, a[i])
	s = ''.join(maped_num)
	print s

Submission status: Accepted

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

field = []

for i in range(h):
	field.append( input())

for i in range(h):
	for j in range(w):
		if field[i][j] == ".":
			hmin = max(i-1, 0)
			hmax = min(i+1, h-1)
			wmin = max(j-1, 0)
			wmax = min(j+1, w-1)
			count = 0
			for m in range(hmin, hmax+1):
				for n in range(wmin, wmax+1):
					if field[m][n] == "#":
						count+=1

#			print (count)
			# field[i][j] = count
			field[i] = field[i][0:j]+ str(count) + field[i][j+1:]


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

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
masu = []
# masu.append(['.' * (W+2)])
# for i in range(H):
#     masu.append(['.' + input() + '.'])
# masu.append(['.' * (W+2)])

masu.append(['.' for i in range(W+2)])
for i in range(H):
    inputline = list(input())
    inputline.insert(0, '.')
    inputline.append('.')
    masu.append(inputline)
masu.append(['.' for i in range(W+2)])

bomap = masu
scan = 0
for i in range(1, H+1):
    for j in range(1, W+1):
        if masu[i][j] == '#':
            continue
        else:
            for x in range(i-1, i+2):
                for y in range(j-1, j+2):
                    if masu[x][y] == '#':
                        scan += 1
            bomap[i][j] = str(scan)
            scan = 0

bomap.pop(0)
bomap.pop(-1)
for line in bomap:
    line.pop(0)
    line.pop(-1)
    for chara in line:
        print(chara, end='')
    print()

Submission status: Accepted

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

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

        v = 0
        for dy in range(-1,2):
            for dx in range(-1,2):
                ny,nx = i+dy,j+dx
                if 0<=ny<h and 0<=nx<w and s[ny][nx]=='#':
                    v += 1
        s[i][j] = str(v)

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

Submission status: Accepted

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

def increment(i, j):
    if 0 <= i < h:
        if 0 <= j < w:
            c[i][j] += 1

h, w = [int(x) for x in input().split()]
c = [[0] * w for _ in range(h)]

for i in range(h):
    for j, m in enumerate(input()):
        if m == '#':
            for i2 in [i - 1, i, i + 1]:
                for j2 in [j - 1, j, j + 1]:
                    increment(i2, j2)
            c[i][j] = -100

for ci in c:
    for cj in ci:
        print('#' if cj < 0 else cj, end='')
    print()

Submission status: Accepted

Solution code:
H, W = list(map(int, input().split()))
field = [[0 for i in range(W+2)] for j in range(H+2)]

for h in range(H):
    L = input()
    for w in range(W):
        if L[w] == "#":
            field[h+1][w+1] = "#"
            for i in range(3):
                for j in range(3):
                    try:
                        field[h+i][w+j] += 1
                    except TypeError:
                        continue
for h in range(1,H+1):
    print("".join(list(map(str, field[h][1:W+1]))))

Submission status: Accepted

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

S = [[]]

for h in range(H):
    S.append([])
    S[-1] = list(input())

del S[0]

for i in range(H):
    for j in range(W):
        if S[i][j] == '.': S[i][j] = 0
        if S[i][j] == '#': S[i][j] = -100
            
for i in range(H):
    for j in range(W):
        if S[i][j] < 0:
            
            if i != 0:
                try: S[i-1][j] += 1
                except: x=1


                try: S[i-1][j+1] += 1
                except: x=1
                    
            if j != 0:
                try: S[i][j-1] += 1
                except: x=1

                try: S[i+1][j-1] += 1
                except: x=1
                
                if i != 0:
                    try: S[i-1][j-1] += 1
                    except: x=1

                
            try: S[i+1][j] += 1
            except: x=1
            
            try: S[i][j+1] += 1
            except: x=1
            
            try: S[i+1][j+1] += 1
            except: x=1
            
            
for i in range(H):
    for j in range(W):
        if S[i][j] < 0: S[i][j] = '#'

for i in range(len(S)):
    for j in range(len(S[i])):
        print(S[i][j], end="")
    print()

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
s = []
n = []
for i in range(H):
    s.append(input())
    n.append([])
    for j in range(W):
        if s[i][j] == ".":
            n[i].append(0)
        else:
            n[i].append(-1)

for i in range(H):
    for j in range(W):
        if n[i][j] == -1:
            for k in range(-1, 2, 1):
                for l in range(-1, 2, 1):
                    if 0 <= i + k and i + k < H and 0 <= j + l and j + l < W:
                        if n[i + k][j + l] != -1:
                                n[i + k][j + l] += 1
for i in range(H):
    ans = ""
    for j in range(W):
        if n[i][j] == -1:
            ans += "#"
        else:
            ans += str(n[i][j])
    print(ans)

Submission status: Accepted

Solution code:
a = list(map(int, input().split()))
y = [list(input()) for i in range(a[0])]
for d in range(a[0]):
    for s in range(a[1]):
        if y[d][s] == ".":
            y[d][s] = "0"
for i in range(a[0]):
    for j in range(a[1]):
        if y[i][j] == "#":
            for k in range(3):
                for l in range(3):
                    if a[0] - 1 >= i - 1 + k >= 0 and a[1] - 1 >= j - 1 + l >= 0:
                        if y[i - 1 + k][j - 1 + l] == "0":
                            y[i - 1 + k][j - 1 + l] = 1
                        elif y[i - 1 + k][j - 1 + l] == "#":
                            pass
                        else:
                            y[i - 1 + k][j - 1 + l] += 1
for b in range(a[0]):
     y[b] = [str(f) for f in y[b]]
     print(''.join(y[b]))

Submission status: Accepted

Solution code:
import sys

H, W = list(map(int, sys.stdin.readline().strip().split(" ")))

first = ""
for i in range(W + 2):
    first += "."
    
l = []
l.append(first)

for i in range(H):
    l.append("." + sys.stdin.readline().strip() + ".")

l.append(first)

result = [[] for i in range(H)]

for i in range(H + 2):
    for j in range(W + 2):
        if (i == 0) or (i == (H + 1)) or (j == 0) or (j == (W + 1)):
            continue
        num = "#"
        if l[i][j] == ".":
            num = int(l[i-1][j-1] == "#") + int(l[i-1][j] == "#") + int(
                l[i-1][j+1] == "#") + int(l[i][j-1] == "#") + int(
                l[i][j+1] == "#") + int(l[i+1][j-1] == "#") + int(
                l[i+1][j] == "#") + int(l[i+1][j+1] == "#")
        result[i-1].append(num)
for i in range(H):
    s = ""
    for j in range(W):
        s += str(result[i][j])
    print(s)

Submission status: Accepted

Solution code:
import sys

def main():
    H, W = map(int, raw_input().split(" "))
    matrix = []
    for _ in range(H):
        matrix.append(list(raw_input()))

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

            num_bombs = 0
            if i - 1 >= 0 and j - 1 >= 0 and matrix[i - 1][j - 1] == "#":
                num_bombs += 1
            if j - 1 >= 0 and matrix[i][j - 1] == "#":
                num_bombs += 1
            if i - 1 >= 0 and matrix[i - 1][j] == "#":
                num_bombs += 1
            if i + 1 < H and j + 1 < W and matrix[i + 1][j + 1] == "#":
                num_bombs += 1
            if j + 1 < W and matrix[i][j + 1] == "#":
                num_bombs += 1
            if i + 1 < H and matrix[i + 1][j] == "#":
                num_bombs += 1
            if i - 1 >= 0 and j + 1 < W and matrix[i - 1][j + 1] == "#":
                num_bombs += 1
            if i + 1 < H and j - 1 >= 0 and matrix[i + 1][j - 1] == "#":
                num_bombs += 1

            matrix[i][j] = str(num_bombs)

    for i in range(H):
        for j in range(W):
            sys.stdout.write(matrix[i][j])
        print ""

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
l = []
for h_ind in range(1, h+1):
    l.append(input())

for h_ind in range(0, h):
    for w_ind in range(0, w):
        if l[h_ind][w_ind] == '#':
            print('#', end='')
            continue
        res = 0
        for dx in range (-1, 2):
            for dy in range(-1, 2):
                if dx == 0 and dy == 0:
                    continue
                if h_ind+dx < 0 or h_ind+dx >= h or w_ind+dy < 0 or w_ind+dy >= w:
                    continue
                if l[h_ind+dx][w_ind+dy] == '#':
                    res +=1
        print(res, end='')
    print('')

Submission status: Accepted

Solution code:
def hoge(x,y,w,h,stage):
    temp = [-1,0,1]
    count = 0
    for i in temp:
        if x + i < 0 or x+i >= h:
            continue
        for j in temp:
            if y + j < 0 or y+j >= w:
                continue
#            print (x+i,y+j)
            if stage[x+i][y+j] == "#":
                count += 1
    return count


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

stage = []
for i in range(0,h):
    stage.append(input())

for i in range(0,h):
    for j in range(0,w):
        if stage[i][j] == "#":
            print("#",end = "")
        else:
            print(hoge(i,j,w,h,stage),end = "")
    print()

Submission status: Accepted

Solution code:
import copy


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

    ans = copy.deepcopy(b)

    for h in range(H):
        for w, s in enumerate(b[h]):
            if s == "#":
                continue

            w_left = max(w - 1, 0)
            h_top = max(h - 1, 0)
            h_bottom = min(h + 2, H)
            n = 0
            for _h in range(h_top, h_bottom):
                n += b[_h][w_left:w + 2].count("#")

            ans[h][w] = str(n)

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

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
S = {}
for _ in range(H):
    S[_] = input()
    
def change(S_str, x, j):
    s_list = list(S_str)
    s_list[j] = str(x.count('#'))
    S_str = "".join(s_list)
    return S_str

for i in range(H):
    for j in range(W):
        s = S[i][j]
        if s == '.':
            if H == 1 and W == 1:
                S[i] = '0'
            elif H == 1 and j == 0:
                x = S[i][j+1]
                S[i] = change(S[i], x, j)
            elif H == 1 and j == W-1:
                x = S[i][j-1]
                S[i] = change(S[i], x, j)
            elif H == 1:
                x = S[i][j-1] + S[i][j+1]
                S[i] = change(S[i], x, j)
            elif W == 1 and i == 0:
                x = S[i+1][j]
                S[i] = change(S[i], x, j)
            elif W == 1 and i == W-1:
                x = S[i-1][j]
                S[i] = change(S[i], x, j)
            elif W == 1:
                x = S[i-1][j] + S[i+1][j]
                S[i] = change(S[i], x, j)
            elif i == 0 and j == 0:
                x = S[i][j+1] + S[i+1][j] + S[i+1][j+1]
                S[i] = change(S[i], x, j)
            elif i == 0 and j == W-1:
                x = S[i][j-1] + S[i+1][j-1] + S[i+1][j]
                S[i] = change(S[i], x, j)
            elif i == 0:
                x = S[i][j-1] + S[i][j+1] + S[i+1][j-1] + S[i+1][j] + S[i+1][j+1]
                S[i] = change(S[i], x, j)
            elif i == H-1 and j == 0:
                x = S[i][j+1] + S[i-1][j] + S[i-1][j+1]
                S[i] = change(S[i], x, j)
            elif i == H-1 and j == W-1:
                x = S[i][j-1] + S[i-1][j-1] + S[i-1][j]
                S[i] = change(S[i], x, j)
            elif i == H-1:
                x = S[i][j-1] + S[i][j+1] + S[i-1][j-1] + S[i-1][j] + S[i-1][j+1]
                S[i] = change(S[i], x, j)
            elif j == 0:
                x = S[i-1][j] + S[i-1][j+1] + S[i][j+1] + S[i+1][j] + S[i+1][j+1]
                S[i] = change(S[i], x, j)
            elif j == W-1:
                x = S[i-1][j-1] + S[i-1][j] + S[i][j-1] + S[i+1][j-1] + S[i+1][j]
                S[i] = change(S[i], x, j)
            else:
                x = 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]
                S[i] = change(S[i], x, j)
                
for k in range(H):
    print(S[k])

Submission status: Accepted

Solution code:
def addone(h,w,m):
	# 指定値の周りに1を足す
	for i in range(-1,2):
		for j in range(-1,2):
			n = m[h+i][w+j]

			#print(h, w, i,j,n)

			if n!="#":
				if n==".": n = "0"
				m[h+i][w+j] = str(int(n)+1)
	#print("---")
	

h, w = map(int, input().split())		# 5 7 2


#m = list( list(input()) for _ in range(h) )
l = list( "." + input() + "." for _ in range(h) )

s = "." * (w+2)

m=[]
m.append( list(s) )
for _ in range(h):
	m.append( list(l[_]) )
m.append( list(s) )

#print(m)


for i in range(1,h+1):
	#print(m[i])
	n = m[i]
	for j in range(1,w+1):
		#print(n[j])
		#print(m[i][j])
		if m[i][j]=="#":
			addone(i,j,m)


for i in range(1,h+1):
	for j in range(1,w+1):
		#print(m[i][j], end='')
		n = m[i][j]
		if n==".": n = "0"
		print(n, end='')
	else:
		print("")

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
S = []
for i in range(H+2):
    if i == 0 or i == (H+1):
        S.append(list("-"*(W+2)))
        continue
    else:
        S.append(list("-" + input() + "-"))


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

        else:
            continue

for i in range(1,H+1):
    print("".join(list(S[i][1:W+1])))

Submission status: Accepted

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

myfield=[]

for i in range(h):
    temp=input()
    myfield.append([])
    for j in range(len(temp)):
        myfield[i].append(temp[j])

myfield2=[]

myfield2.append([])
myfield2[0].append("-")
for i in range(w):
    myfield2[0].append("-")
myfield2[0].append("-")
for i in range(h):
    myfield2.append([])
    myfield2[i+1].append("-")
    for j in range(w):
        myfield2[i+1].append(myfield[i][j])
    myfield2[i+1].append("-")
myfield2.append([])
myfield2[h+1].append("-")
for i in range(w):
    myfield2[h+1].append("-")
myfield2[h+1].append("-")

for i in range(h):
    for j in range(w):
        if myfield[i][j]=="#":
            continue
        temp=0
        for k in range(3):
            for l in range(3):
                if myfield2[i+k][j+l]=="#":
                    temp+=1
        myfield[i][j]=str(temp)

for i in range(h):
    temp=""
    for j in range(w):
        temp+=myfield[i][j]
    print(temp)

Submission status: Accepted

Solution code:
from sys import stdin, stdout
from collections import defaultdict
def readLine_str_list():return list(map(str, stdin.readline().split()))
def readLine_int_list():return list(map(int, stdin.readline().split()))
def readAll_str(): return list(list(map(str,i.split())) for i in stdin.read().split("\n"))
def g_twoD_list(p,q): return [[0 for i in range(p)] for j in range(q)]


def main():
    h,w = readLine_int_list()
    a = g_twoD_list(w,h)
    b = defaultdict(lambda: 0)
    _h = 0
    _w = 0
    for l in readAll_str():
        for i in l:
            _w = 0
            for j in i:
                b[(_h,_w)] = j
                _w += 1
            _h += 1
            
    dir_b = [(-1,0), (1,0), (0,-1), (0,1), (-1,-1), (-1,1), (1,-1), (1,1)]
    for i in range(h):
        for j in range(w):
            cnt = 0
            for d in dir_b:
                r = b[(i+d[0], j+d[1])]
                if r == '#':
                    cnt += 1
            if b[(i,j)] == '.':
                b[(i,j)] = str(cnt)
    # print(b)
    for i in b:
        if 0 <= i[0] < h and 0 <= i[1] < w:
            a[i[0]][i[1]] = b[i]
            
    for i in a:
        print(''.join(i))
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def i1():
 return int(input())
def i2():
 return [int(i) for i in input().split()]
[h,w]=i2()
s=[]
for i in range(h):
 s.append(list(input()))
for i in range(h):
 ss=""
 for j in range(w):
   a=0
   if s[i][j]==".":
      if i>0 and s[i-1][j]=="#":
         a+=1
      if j>0 and s[i][j-1]=="#":
         a+=1
      if i>0 and j>0 and s[i-1][j-1]=="#":
         a+=1
      if i<h-1 and s[i+1][j]=="#":
         a+=1
      if j<w-1 and s[i][j+1]=="#":
         a+=1
      if i<h-1 and j<w-1 and  s[i+1][j+1]=="#":
         a+=1
      if i>0 and j<w-1 and s[i-1][j+1]=="#":
         a+=1
      if i<h-1 and j>0 and s[i+1][j-1]=="#":
         a+=1
      ss+=str(a)
   else:
      ss+="#" 
 print(ss)

Submission status: Accepted

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

Slist = [list(S[i]) for i in range(H)]

ans = [[0 for i in range(W+2)] for j in range(H+2)]
for i in range(H):
    for j in range(W):
        if(Slist[i][j] == '#'):
            ans[i][j] += 1
            ans[i][j+1] += 1
            ans[i][j+2] += 1
            ans[i+1][j] += 1
            ans[i+1][j+2] += 1
            ans[i+2][j] += 1
            ans[i+2][j+1] += 1
            ans[i+2][j+2] += 1

for i in range(H):
    ansstr =""
    for j in range(W):
        if(Slist[i][j] == '.'):
            ansstr += str(ans[i+1][j+1])
        elif(Slist[i][j] == '#'):
            ansstr += Slist[i][j]
    print(ansstr)