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 = []
for _ in range(h):
	s.append(list(input()))
    
if (h == 1)&(w==1):
    if s[0][0] == ".":
        s[0][0] = "0"

elif (h == 1)&(w!=1):
    for j in range(w):
        if j == 0:
            s[0][j] = s[0][j].replace(".",str(s[0][j+1].count("#")))
        elif j == w-1:
            s[0][j] = s[0][j].replace(".",str(s[0][j-1].count("#")))
        else:
            s[0][j] = s[0][j].replace(".",str([s[0][j-1],s[0][j+1]].count("#")))

elif (h != 1)&(w==1):
    for i in range(h):
        if i == 0:
            s[i][0] = s[i][0].replace(".",str(s[i+1][0].count("#")))
        elif i == h-1:
            s[i][0] = s[i][0].replace(".",str(s[i-1][0].count("#")))
        else:
            s[i][0] = s[i][0].replace(".",str([s[i-1][0],s[i+1][0]].count("#")))
else:
    for i in range(len(s)):
        if i == 0:
            for j in range(w):
                if j == 0:
                    s[i][j] = s[i][j].replace(".",str([s[i][j+1],s[i+1][j],s[i+1][j+1]].count("#")))
                elif j == w-1:
                    s[i][j] = s[i][j].replace(".",str([s[i][j-1],s[i+1][j],s[i+1][j-1]].count("#")))
                else:
                    s[i][j] = s[i][j].replace(".",str([s[i][j-1],s[i][j+1],s[i+1][j],s[i+1][j+1],s[i+1][j-1]].count("#")))
        elif i == h-1:
            for j in range(w):
                if j == 0:
                    s[i][j] = s[i][j].replace(".",str([s[i][j+1],s[i-1][j],s[i-1][j+1]].count("#")))
                elif j == w-1:
                    s[i][j] = s[i][j].replace(".",str([s[i][j-1],s[i-1][j],s[i-1][j-1]].count("#")))
                else:
                    s[i][j] = s[i][j].replace(".",str([s[i][j-1],s[i][j+1],s[i-1][j],s[i-1][j+1],s[i-1][j-1]].count("#")))
        else:
            for j in range(w):
                if j == 0:
                    s[i][j] = s[i][j].replace(".",str([s[i][j+1],s[i-1][j],s[i-1][j+1],s[i+1][j],s[i+1][j+1]].count("#")))
                elif j == w-1:
                    s[i][j] = s[i][j].replace(".",str([s[i][j-1],s[i-1][j],s[i-1][j-1],s[i+1][j],s[i+1][j-1]].count("#")))
                else:
                    s[i][j] = s[i][j].replace(".",str([s[i][j-1],s[i][j+1],s[i-1][j],s[i-1][j+1],s[i-1][j-1],s[i+1][j],s[i+1][j+1],s[i+1][j-1]].count("#")))

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

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
S=[input() for _ in range(H)]
ans=[[0]*W for _ in range(H)]
x=(-1,0,1,-1,0,1,-1,0,1)
y=(1,1,1,0,0,0,-1,-1,-1)
for i in range(H):
  for j in range(W):
    if S[i][j]==".":
      for k in range(9):
        a=i+y[k]
        b=j+x[k]
        if 0<=a<H and 0<=b<W:
          if S[a][b]=="#":
            ans[i][j]+=1
for i in range(H):
  for j in range(W):
    if S[i][j]=="#":
      print("#",end="")
    else:
      print(ans[i][j],end="")
  print()

Submission status: Accepted

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    H, W = map(int, readline().split())

    grid = ["." * (W + 2)]

    for _ in range(H):
        s = "." + input() + "."
        grid.append(s)
    grid.append("." * (W + 2))

    res = []
    for row in range(1, H + 1):
        cur = ""
        for col in range(1, W + 1):
            if grid[row][col] == "#":
                cur += "#"
            else:
                cnt = 0
                for r in (row - 1, row, row + 1):
                    for c in (col - 1, col, col + 1):
                        if grid[r][c] == "#":
                            cnt += 1
                cur += str(cnt)
        res.append(cur)

    for x in res:
        print(x)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

result = []
for i, r in enumerate(rl):
    result_r = ""
    pre_r = rl[i - 1] if i - 1 >= 0 else ""
    next_r = rl[i + 1] if i + 1 < H else ""
    for j, p in enumerate(r):
        if p == "#":
            result_r += "#"
            continue
        pre_j = j - 1 if j - 1 >= 0 else 0
        next_j = j + 2
        around_str = pre_r[pre_j:next_j] + r[pre_j:next_j] + next_r[pre_j:next_j]
        result_r += str(around_str.count("#"))
    result.append(result_r)

print("\n".join(result))

Submission status: Accepted

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

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

ans = s.copy()
for i in range(h):
    ans[i] = list(ans[i])

for x in range(h):
    for y in range(w):
        if s[x][y] == '.':
            num = 0
            for dx in [-1, 0, 1]:
                for dy in [-1, 0, 1]:
                    if 0 <= x + dx < h and 0 <= y + dy < w and s[x+dx][y+dy] == '#':
                        num += 1
            ans[x][y] = str(num)

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

Submission status: Accepted

Solution code:

def mine_count(x, y, ans):
    ans[y][x] = 0
    for nx, ny in (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1):
        if 0 <= y+ny < H and 0 <= x+nx < W:
            if ans[y+ny][x+nx] == "#":
                ans[y][x] += 1
    return ans


H, W = map(int, input().split())
S = [list(input()) for _ in range(H)]
ans = S
for i in range(H):
    for j in range(W):
        if S[i][j] == ".":
            ans = mine_count(j, i, ans)

for row in ans:
    for item in row:
        print(item, end="")
    print()

Submission status: Accepted

Solution code:
h,w = map(int,input().split())
grid = [""]*h
for i in range(h):
    grid[i] = list(input())
# print(grid)
search = [(row,col) for row in range(-1,2) for col in range(-1,2) if not(row == 0 and col == 0)]
# print(search)

for i in range(h):
    ans = ""
    for j in range(w):
        if(grid[i][j] == "."):
            bomb = 0
            for k in range(8):
                row,col = search[k]
                if(0<=i+row<h and 0<=j+col<w):
                    if(grid[i+row][j+col] == "#"):
                        bomb += 1
            grid[i][j] = bomb
        ans+=str(grid[i][j])
    print(ans)

Submission status: Accepted

Solution code:
h,w = map(int, input().split())
l = [[] for _ in range(h+2)]
l[0] = list("."*(w+2))
l[h+1] = list("."*(w+2))
for i in range(1,h+1):
  l[i] = list(("." + input() + "."))
for j in range(1,h+1):
  for k in range(1,w+1):
    c = []
    if l[j][k] == ".":
      c += [l[j-1][k-1], l[j-1][k], l[j-1][k+1], l[j][k-1], l[j][k+1], l[j+1][k-1], l[j+1][k], l[j+1][k+1]]
      l[j][k] = str(c.count("#"))
for i in range(1,h+1):
  ln = l[i][1:w+1]
  s = "".join(ln)
  print(s)

Submission status: Accepted

Solution code:
h, w = (int(x) for x in input().split())
s = []
ans = []
rev = ""
for row in range(1, h+1):
    for col, t in enumerate(input()):
        s.append([(row,col+1),t])

for index, factor in enumerate(s):
    count =0
    if factor[1] != "#":
        if w == 1:
            for point in [index-1, index+1]:
                if 0 <= point and point < len(s) and s[point][1] == "#":
                    count += 1
        elif (index+1)%w == 1:
            for point in [index +1,index -w+1, index -w, index +w, index +w+1]:
                if 0 <= point and point < len(s) and s[point][1] == "#":
                    count += 1
        elif (index+1)%w == 0:
            for point in [index -1,index -w, index -w-1, index +w-1, index +w]:
                if 0 <= point and point < len(s) and s[point][1] == "#":
                    count += 1
        else:
            for point in [index -1, index +1,index -w+1, index -w, index -w-1, index +w-1, index +w, index +w+1]:
                if 0 <= point and point < len(s) and s[point][1] == "#":
                    count += 1
        ans.append(count)
    else:
        ans.append("#")

while(ans != []):
    for num in range(w):
        rev += str(ans[0])
        del ans[0]
    rev += "\n"

print(rev)

Submission status: Accepted

Solution code:
dx = [1, 0, -1, 0, 1, -1, -1, 1]
dy = [0, 1, 0, -1, 1, 1, -1, -1]

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

# 各マス (i, j) について順に処理
for i in range(H):
    for j in range(W):
        if S[i][j] != '.':
            continue
        counter = 0
        for d in range(8):
            ni = i + dx[d]
            nj = j + dy[d]
            if ni < 0 or ni >= H or nj < 0 or nj >= W:
                continue
            if S[ni][nj] == '#':
                counter += 1
        S[i] = S[i].replace('.', str(counter), 1)

for row in S:
    print(row)

Submission status: Accepted

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

def count(i,j):
    if l[i][j] == "#":
        return "#"
    c = 0
    for n in range(i-1,i+2):
        for m in range(j-1,j+2):
            if l[n][m] == "#":
                c += 1
    return str(c)

ans = ["".join([count(i,j) for j in range(1,1+w)]) for i in range(1,1+h)]

print("\n".join(ans))

Submission status: Accepted

Solution code:
# 0: 下、1: 右、2: 上、3: 左、4: 右下、5: 右上、6: 左上、7: 左下
dx = [1, 0, -1, 0, 1, -1, -1, 1]
dy = [0, 1, 0, -1, 1, 1, -1, -1]

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

# Python3 では str 型の要素の書き換えはできない
# 答えを格納する二次元配列を別途用意する ('.' のところは 0 とする)
result = [[0 if v == '.' else '#' for v in row] for row in S]

# 各マス (i, j) について順に処理
for i in range(H):
    for j in range(W):
        if S[i][j] != '.':
            continue
        for d in range(8):
            ni = i + dx[d]
            nj = j + dy[d]
            if ni < 0 or ni >= H or nj < 0 or nj >= W:
                continue
            if S[ni][nj] == '#':
                result[i][j] += 1

for row in result:
    # 出力形式に合わせて出力
    print(*row, sep = '')

Submission status: Accepted

Solution code:
dx = [1, 0, -1, 0, 1, -1, -1, 1]
dy = [0, 1, 0, -1, 1, 1, -1, -1]

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

# Python3 では str 型の要素の書き換えはできない
# 答えを格納する二次元配列を別途用意する ('.' のところは 0)
result = [[0 if v == '.' else '#' for v in row] for row in S]

# 各マス (i, j) について順に処理
for i in range(H):
    for j in range(W):
        if S[i][j] != '.':
            continue
        for d in range(8):
            ni = i + dx[d]
            nj = j + dy[d]
            if ni < 0 or ni >= H or nj < 0 or nj >= W:
                continue
            if S[ni][nj] == '#':
                result[i][j] += 1

for row in result:
    print(*row, sep = '')

Submission status: Accepted

Solution code:
H,W=list(map(int,input().split()))
l=[list(input()) for i in range(H)]
ans_l=[[0]*W for i in range(H)]
for i in range(H):
   for j in range(W):
      if l[i][j] == ".":
         tmp=0
         for x in range(max(0,j-1),min(W-1,j+1)+1):
            for y in range(max(0,i-1),min(H-1,i+1)+1):
               if l[y][x]=="#":
                  tmp+=1
         ans_l[i][j]=str(tmp)
      else:
         ans_l[i][j]="#"
for i in ans_l:
   print(*i,sep="")

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
a = [input() for i in range(h)]
for i in range(h):
  b = ""
  for j in range(w):
    if a[i][j] == "#":
      b += "#"
    else:
      b += str(sum(k[max(0, j-1):min(w, j+2)].count("#") for k in a[max(0, i-1):min(h, i+2)]))
  print(b)

Submission status: Accepted

Solution code:
import sys, itertools
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = 10**20
def I(): return int(input())
def F(): return float(input())
def S(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LS(): return input().split()

def resolve():
    H, W = LI()
    s = [list(S()) for _ in range(H)]

    for i, j in itertools.product(range(H), range(W)):
        if s[i][j] != '#':
            cnt = 0
            for k, l in itertools.product(range(-1, 2), repeat=2):
                if 0 <= i + k < H and 0 <= j + l < W:
                    if s[i+k][j+l] == '#':
                        cnt += 1
            s[i][j] = str(cnt)

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

if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
h,w = map(int,input().split())
l = [['*']*(w+2)]
for i in range(h):
    l.append(['*']+list(input())+['*'])
l.append(['*']*(w+2))


for i in range(1,h+1):
    s = ''
    for j in range(1,w+1):
        directions = [(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1),(-1,0),(-1,1)]
        alist = [(i+dir[0],j+dir[1]) for dir in directions]
        cnt = 0
        for a in alist:
            if l[a[0]][a[1]] == '#':
                cnt += 1
        if l[i][j] == '#':
            s += '#'
        else:
            s += str(cnt)
    print(s)

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))
dx=[-1,0,1,1,1,0,-1,-1]
dy=[1,1,1,0,-1,-1,-1,0]
ans=[]
for i in range(1,h+1):
    wp=""
    for j in range(1,w+1):
        if s[i][j]=="#":
            wp+="#"
            continue
        count=0
        for k in range(8):
            if s[i+dy[k]][j+dx[k]]=="#":
                count+=1
        wp+=str(count)
    ans.append(wp)
print(*ans,sep="\n")

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
s = []
for i in range(H):
    a = list(input())
    s.append(a)
for i in range(H):
    for j in range(W):
        count = 0
        if s[i][j] == ".":
            for k in range(i-1,i+2):
                for l in range(j-1,j+2):
                    if (0 <= k <= H-1) and (0 <= l <= W-1) and s[k][l] == "#":
                        count += 1
            s[i][j] = str(count)
for i in range(H):
    print("".join(s[i]))

Submission status: Accepted

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

for x,y in itertools.product(range(W),range(H)):
    if S[y][x]==".":
        res=0
        for i,j in itertools.product(range(-1,2),range(-1,2)):
            if 0<=x+i and x+i<W and 0<=y+j and y+j<H:
                if S[y+j][x+i]=="#":
                    res+=1
        
        S[y][x]=res

for j in range(H):
    L=[str(a) for a in S[j]]
    print(''.join(L))

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):
        a = 0
        if s[i][j] == '.':
            for k in range(i - 1, i + 2):
                for l in range(j - 1, j + 2):
                    if (0 <= k and k <= h - 1) and (0 <= l and l <= w - 1) and s[k][l] == '#':
                        a += 1
            s[i][j] = str(a)
for m in range(h):
    print(''.join(s[m]))

Submission status: Accepted

Solution code:
import sys

input = sys.stdin.readline

def main():
    ans = []
    b = "#"
    h, w = map(int, input().split())
    s = [input().rstrip('\n') for _ in range(h)]
    for y in range(h):
        ans.append([])
        for x in range(w):
            if s[y][x] == b:
                ans[y].append(b)
            else:
                ans[y].append(0)
    for y in range(h):
        for x in range(w):
            if s[y][x] == b:
                if y > 0 and x > 0 and ans[y-1][x-1] != b:
                    ans[y-1][x-1] += 1
                if y > 0 and ans[y-1][x] != b:
                    ans[y-1][x] += 1
                if y > 0 and x < w - 1 and ans[y-1][x+1] != b:
                    ans[y-1][x+1] += 1
                if x > 0 and ans[y][x-1] != b:
                    ans[y][x-1] += 1
                if x < w - 1 and ans[y][x+1] != b:
                    ans[y][x+1] += 1
                if y < h - 1 and x > 0 and ans[y+1][x-1] != b:
                    ans[y+1][x-1] += 1
                if y < h - 1 and ans[y+1][x] != b:
                    ans[y+1][x] += 1
                if y < h - 1 and x < w - 1 and ans[y+1][x+1] != b:
                    ans[y+1][x+1] += 1
    for y in range(h):
        for x in range(w):
            if ans[y][x] == 0 and s[y][x] == b:
                ans[y][x] = "#"
            else:
                ans[y][x] = str(ans[y][x])
        print(''.join(ans[y]))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
S = [list(input()) for _ in range(H)]
#print(S)
ans = [[0]*W for _ in range(H)]
for i in range(H):
    for j in range(W):
        if S[i][j] == "#":
            ans[i][j] = "#"
        else:
            c = 0
            for dx in [-1,0,1]:
                for dy in [-1,0,1]:
                    if 0 <= i+dy <= H-1 and 0 <= j+dx <= W-1 and S[i+dy][j+dx] == "#":
                        c += 1
            ans[i][j] = str(c) 
for i in range(H):
    output = "".join(ans[i])
    print(output)

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
s = []
for i in range(H):
    a = list(input())
    s.append(a)
for i in range(H):
    for j in range(W):
        count = 0
        if s[i][j] == ".":
            for k in range(i-1,i+2):
                for l in range(j-1,j+2):
                    if (0 <= k <= H-1) and (0 <= l <= W-1) and s[k][l] == "#":
                        count += 1
            s[i][j] = str(count)
for i in range(H):
    print("".join(s[i]))

Submission status: Accepted

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

Submission status: Accepted

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

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

for h in range(H):
    for w in range(W):
        if S[h][w] == "#":
            continue
        else:
            cnt = 0
            for k in range(8):
                next_h = h+dh[k]
                next_w = w+dw[k]
                if not(0<= next_h <= H-1) or not(0<= next_w <= W-1):
                    continue
                elif S[next_h][next_w] == "#":
                    cnt += 1
        S[h][w] = str(cnt)
        
for s in S:
    print("".join(s))

Submission status: Accepted

Solution code:
H, W = (int(x) for x in input().split())
S = [input() for _ in range(H)]
ans = [''] * H  
for i in range(H):
    for j in range(W):
        if S[i][j] == '#':
            ans[i] += '#'
            continue
        bom = 0
        for k in range(3):
            for l in range(3):
                if 0 <= i-1+k < H and 0 <= j-1+l < W:
                    if S[i-1+k][j-1+l] == '#':
                        bom += 1
        ans[i] += str(bom)
for s in ans:
    print(s)

Submission status: Accepted

Solution code:
#6 B - Minesweeper
H,W = map(int,input().split())
S = [list(input()) for _ in range(H)]

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

for h in range(H):
    for w in range(W):
        #マス(h,w)について
        if S[h][w] == '#':
            continue
        else:
            cnt= 0
            for v in range(8):
                nxt_h = h + dh[v]
                nxt_w = w + dw[v]
                if not(-1<nxt_h<H) or not(-1<nxt_w<W):
                    continue
                elif S[nxt_h][nxt_w] == '#':
                    cnt += 1
                S[h][w] = str(cnt)
if H==1 and W==1:
    print(0)
else:
    for i in S:
        print(''.join(i))

Submission status: Accepted

Solution code:
def sarch(i,j):
    cnt=0
    i1=[i-1,i,i+1]
    j1=[j-1,j,j+1]
    for x in range(3):
        for y in range(3):
            if S[i1[x]][j1[y]]=="#":
                cnt+=1
    return cnt

import numpy as np
H,W=map(int,input().split())
S=np.array([list(str(input())) for i in range(H)])


gyo_0=np.array(["."]*W)
retu_0=np.array([["."]]*(H+2))

S=np.vstack((gyo_0,S))
S=np.vstack((S,gyo_0))
S=np.hstack((retu_0,S))
S=np.hstack((S,retu_0))

for i in range(1,H+1):
    for j in range(1,W+1):
        if S[i][j]==".":
            S[i][j]=sarch(i,j)
        print(S[i][j],end="")
    print()

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
s=[input() for i in range(h)]
ss=[[0 for _ in range(w+2)] for _ in range(h+2)]
for j in range(w):
    for i in range(h):
        ss[i+1][j+1]=s[i][j]
s=[[0 for _ in range(w)] for _ in range(h)]
for j in range(1,w+1):
    for i in range(1,h+1):
        for a in range(-1,2):
            for b in range(-1,2):
                if a==0 and b ==0:
                    continue
                if ss[i+a][j+b]=='#':
                    s[i-1][j-1]+=1
for j in range(w):
    for i in range(h):
        if ss[i+1][j+1]=='#':
            s[i][j]='#'
for i,d in enumerate(s):
    d=map(str,d)
    print(''.join(d))

Submission status: Accepted

Solution code:
import bisect,collections,copy,itertools,math,string
import sys
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())
def main():
    h,w = LI()
    board = [["." for _ in range(w+2)]]
    for _ in range(h):
        s = S()
        s = list(s)
        s = ["."] + s + ["."]
        board.append(s)
    board.append(["." for _ in range(w+2)])

    exp = [[1,0],[0,1],[-1,0],[0,-1],[1,1],[1,-1],[-1,1],[-1,-1]]
    for y in range(1,h+1):
        for x in range(1,w+1):
            if board[y][x] == ".":
                cnt = 0
                for u,r in exp:
                    if board[y-u][x-r] == "#":
                        cnt += 1
                board[y][x] = str(cnt)

    for line in board[1:-1]:
        line = "".join(line[1:-1])
        print(line)
main()

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
        else:
            count = 0
            for k in range(-1,2,1):
                for l in range(-1,2,1):
                    if j+k<0 or i+l<0 or j+k>=W or i+l>=H:
                        continue
                    if S[i+l][j+k]=="#":
                        count+=1
            S[i][j]=str(count)

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

Submission status: Accepted

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

l=[]
for i in range(H):
    l.append(list(input()))

for i in range(H):
    for j in range(W):
        #地雷数のカウンタ
        c = 0

        #'#'の場合は何もしない
        if l[i][j]=='#':
            pass
        
        #'#'以外の場合
        else:
            #左上
            if 0<i and 0<j and l[i-1][j-1]=='#':
                c+=1
            #上
            if 0<i and l[i-1][j]=='#':
                c+=1
            #右上
            if 0<i and j<W-1 and l[i-1][j+1]=='#':
                c+=1
            #左
            if 0<j and l[i][j-1]=='#':
                c+=1
            #右
            if j<W-1 and l[i][j+1]=='#':
                c+=1
            #左下
            if i<H-1 and 0<j and l[i+1][j-1]=='#':
                c+=1
            #右下
            if i<H-1 and j<W-1 and l[i+1][j+1]=='#':
                c+=1
            #下
            if i<H-1 and l[i+1][j]=='#':
                c+=1

            #地雷接数
            l[i][j]=str(c)

#出力
for i in range(H):
    print(''.join(l[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(len(S)):
    for j in range(len(S[i])):
        a=0
        if S[i][j]=='.':
            for k in range(i-1,i+2):
                for l in range(j-1,j+2):
                    if (0<=k and k<=len(S)-1) and (0<=l and l<=len(S[i])-1) and S[k][l]=='#':
                        a+=1
            S[i][j]=str(a)
for i in range(len(S)):
    print(''.join(S[i]))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import numpy as np
import sys
from collections import deque
from collections import defaultdict
import heapq
import collections
import itertools
import bisect
from scipy.special import comb
import copy
sys.setrecursionlimit(10**6)


def zz():
    return list(map(int, sys.stdin.readline().split()))


def z():
    return int(sys.stdin.readline())


def S():
    return sys.stdin.readline()[:-1]


def C(line):
    return [sys.stdin.readline() for _ in range(line)]


H, W = zz()
table = []
for i in range(H):
    table.append(input())
ans_table = [[0]*W for _ in range(H)]
dx = [-1, 0, 1, -1, 1, -1, 0, 1]
dy = [-1, -1, -1, 0, 0, 1, 1, 1]
for i in range(H):
    for j in range(W):
        tmp = 0
        if (table[i][j] == '.'):
            for x, y in zip(dx, dy):
                if (i + x >= H or j+y >= W or i + x < 0 or j+y < 0):
                    continue
                if (table[i + x][j + y] == '#'):
                    tmp += 1
            ans_table[i][j] = tmp
        else:
            ans_table[i][j] = '#'


for _table in ans_table:
    print(*_table, sep='')

Submission status: Accepted

Solution code:
import sys
import re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
INPUT = lambda: sys.stdin.readline().rstrip()
INT = lambda: int(INPUT())
MAP = lambda: map(int, INPUT().split())
S_MAP = lambda: map(str, INPUT().split())
LIST = lambda: list(map(int, INPUT().split()))
S_LIST = lambda: list(map(str, INPUT().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

H, W = MAP()
S = ['.'*(W + 2), *['.' + INPUT() + '.' for _ in range(H)], '.'*(W + 2)]

ans = ["" for _ in range(H)]
dy = [0, -1, -1, -1, 0, 1, 1, 1]
dx = [1, 1, 0, -1, -1, -1, 0, 1]
for i in range(H):
    for j in range(W):
        if S[i+1][j+1] == '#':
            ans[i] += '#'
            continue

        cnt = 0
        for y, x in zip(dy, dx):
            if S[i+1+y][j+1+x] == '#':
                cnt += 1

        ans[i] += str(cnt)

print(*ans, sep='\n')

Submission status: Accepted

Solution code:
import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, gcd
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from functools import reduce
from bisect import bisect_left, insort_left
from heapq import heapify, heappush, heappop

INPUT = lambda: sys.stdin.readline().rstrip()
INT = lambda: int(INPUT())
MAP = lambda: map(int, INPUT().split())
S_MAP = lambda: map(str, INPUT().split())
LIST = lambda: list(map(int, INPUT().split()))
S_LIST = lambda: list(map(str, INPUT().split()))

sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7


def main():
    H, W = MAP()
    S = ['.'*(W + 2), *['.' + INPUT() + '.' for _ in range(H)], '.'*(W + 2)]

    ans = ["" for _ in range(H)]
    dy = [0, -1, -1, -1, 0, 1, 1, 1]
    dx = [1, 1, 0, -1, -1, -1, 0, 1]
    for i in range(H):
        for j in range(W):
            if S[i+1][j+1] == '#':
                ans[i] += '#'
                continue

            cnt = 0
            for y, x in zip(dy, dx):
                if S[i+1+y][j+1+x] == '#':
                    cnt += 1

            ans[i] += str(cnt)

    print(*ans, sep='\n')


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
s=[input() for _ in range(H)]
S=[]
S.append(['.' for _ in range(W+2)])
for i in range(H):
    s[i]='.'+s[i]+'.'
    S.append(list(s[i]))
S.append(['.' for _ in range(W+2)])
for i in range(1,H+1):
    for j in range(1,W+1):
        cnt=0
        if S[i][j]=='.':
            for k in range(-1,2):
                for l in range(-1,2):
                    if S[i+k][j+l]=='#':
                        cnt+=1
            S[i][j]=str(cnt)
for i in range(1,H+1):
    print(''.join(S[i][1:W+1]))

Submission status: Accepted

Solution code:
import math
import numpy as np
import sys
import os
from operator import mul

sys.setrecursionlimit(10**7)

def _S(): return sys.stdin.readline().rstrip()
def I(): return int(_S())
def LS(): return list(_S().split())
def LI(): return list(map(int,LS()))

if os.getenv("LOCAL"):
    inputFile = basename_without_ext = os.path.splitext(os.path.basename(__file__))[0]+'.txt'
    sys.stdin = open(inputFile, "r")
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353    

# grid
# N = I()
H,W = LI()
S = [list(_S()) for _ in range (H)]

# ans = np.zeros(shape=(H,W))
def replace(x, y):
    # 移動する8方向をループ
    count = 0
    for dx in range(-1, 2):
        for dy in range(-1, 2):
            # x, y 方向それぞれに dx, dy 移動した場所を (nx, ny) とする
            nx = x + dx
            ny = y + dy

            if 0 <= nx and nx < H and 0 <= ny and ny < W and S[nx][ny] == "#":
                count += 1
    S[x][y]=str(count)


for i in range(H):
    for j in range(W):
        if not (S[i][j] == "#"):
            replace(i,j)

for row in S:
  print(*row,sep='')