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 = ["."*(w+2) for _ in range(h+2)]
for i in range(1, h+1):
  s[i] = "."+input()+"."
#準備完了 マス目は周りに1つ .が追加されている
kekka = [["#" for i in range(w)] for _ in range(h)]
#結果を収納するところ
for i in range(1, h+1):
  for j in range(1, w+1):
    if s[i][j]=="#":
      pass
    else:
      cnt = 0
      for x in range(-1, 1+1):
        for y in range(-1, 1+1):
          if (x!=0 or y!=0) and s[i+x][j+y]=="#":
            cnt += 1
      kekka[i-1][j-1] = str(cnt)
for i in range(h):
  print("".join(kekka[i]))

Submission status: Accepted

Solution code:
h,w = map(int,input().split())
s = ["."*(w+2) for _ in range(h+2)]
for i in range(1, h+1):
  s[i] = "."+input()+"."
#準備完了 マス目は周りに1つ .が追加されている
kekka = [["#" for i in range(w)] for _ in range(h)]
#結果を収納するところ
for i in range(1, h+1):
  for j in range(1, w+1):
    if s[i][j]=="#":
      pass
    else:
      cnt = 0
      cnt += [0,1][s[i-1][j-1]=="#"]
      cnt += [0,1][s[i-1][j]=="#"]
      cnt += [0,1][s[i-1][j+1]=="#"]
      cnt += [0,1][s[i][j-1]=="#"]
      cnt += [0,1][s[i][j+1]=="#"]
      cnt += [0,1][s[i+1][j-1]=="#"]
      cnt += [0,1][s[i+1][j]=="#"]
      cnt += [0,1][s[i+1][j+1]=="#"]
      kekka[i-1][j-1] = str(cnt)
for i in range(h):
  print("".join(kekka[i]))

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
s = [["a"]*(w + 2)]

for i in range(h):
    a = list("a" + input() + "a")
    s.append(a)

s.append(["a"]*(w + 2))

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

for i in range(1, h + 1):
    print("".join(s[i][1:-1]))

Submission status: Accepted

Solution code:
# abc075_b.py
'''
こういうのきれいに速く実装できるようになりたい…
'''
def search_mine(i,j,glid):
    cnt = 0
    if glid[i][j] == "#":
        return "#"
    if glid[i-1][j-1] == "#":
        cnt += 1
    if glid[i-1][j] == "#":
        cnt += 1
    if glid[i-1][j+1] == "#":
        cnt += 1
    if glid[i][j-1] == "#":
        cnt += 1
    if glid[i][j] == "#":
        cnt += 1
    if glid[i][j+1] == "#":
        cnt += 1
    if glid[i+1][j-1] == "#":
        cnt += 1
    if glid[i+1][j] == "#":
        cnt += 1
    if glid[i+1][j+1] == "#":
        cnt += 1
    return cnt


H,W = map(int,input().split())
glid =[]
glid.append(list("."*(W+2)))
for i in range(H):
    glid.append(list("." + input() + "."))
glid.append(list("."*(W+2)))



for i in range(1,H+1):
    for j in range(1,W+1):
        glid[i][j] = search_mine(i,j,glid)
for i,v in enumerate(glid):
    if i == 0 or i == H+1:
        continue
    ans = ""
    for j,c in enumerate(v):
        if j == 0 or j == W+1:
            continue
        ans += str(c)
    print(ans)

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
mat=[[False]*(W+2)]
for i in range(H):
  array=[x=="#" for x in input()]
  mat.append([False]+array+[False])
mat.append([False]*(W+2))
#print(mat)

for i in range(1,H+1):
  ans_list=[]
  for j in range(1,W+1):
    if mat[i][j]:
      ans_list.append("#")
    else:
      ans=0
      for x in range(-1,2):
        for y in range(-1,2):
          if mat[i+x][j+y]:
            ans+=1
      ans_list.append(str(ans))
  print("".join(ans_list))

Submission status: Accepted

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

ANS = [['#'] * W for _ in range(H)]
nxt = [-1,0,1]
for r in range(H):
  for c in range(W):
    cnt = 0
    if S[r][c] == '#':
      continue
    for x,y in itertools.product(nxt,repeat=2):
      if x == 0 and y == 0:
        continue
      if not 0 <= r+x < H:
        continue
      if not 0 <= c+y < W:
        continue
      if S[r+x][c+y] == '#':
        cnt += 1
    ANS[r][c] = cnt

for i in range(H):
  print("".join(map(str,ANS[i])))

Submission status: Accepted

Solution code:
def myAnswer(H:int,W:int,S:list) -> None:
   XY = [[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]]
   index = []
   ans = [[0]*W for _ in range(H)]
   for i in range(H):
      for j in range(W):
         if(S[i][j] == "#"):
            ans[i][j] = "#"
            index.append([i,j])
   for i,j in index:
      for x,y in XY:
         if(0 > (j + x) or (j + x) >= W or 0 > (i + y) or (i + y) >= H):
            continue
         elif(ans[y+i][x+j]== "#"):
            continue
         else:
            ans[y + i][x + j] += 1
   for a in ans:
      string = ""
      for s in a:
         string += str(s)
      print(string)

def modelAnswer(H:int,W:int,S:list) -> int:
   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(S[i][j] == "#"):continue

         num = 0
         for d in range(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] == "#"): num+=1
         
         S[i][j] = str(num )
   for s in S:
      ans = ""
      for a in s:
         ans += a
      print(ans)
def main():
   H,W = map(int,input().split())
   S = [list(input()) for _ in range(H)]
   myAnswer(H,W,S[:])
if __name__ == '__main__':
   main()

Submission status: Accepted

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

for i in range(H):
  for j in range(W):
    if S[i][j] == '#':
      continue
    cnt = 0
    for n in range(8):
      ni = i + dx[n]
      nj = j + dy[n]
      if ni < 0 or H <= ni or nj < 0 or W <= nj:
        continue
      if S[ni][nj] == '#':
        cnt += 1
    S[i][j] = str(cnt)


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

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 8)
INF = float('inf')
MOD = 10 ** 9 + 7

def main():
    H, W = map(int, readline().split())
    S = list(list(input()) for _ in range(H))
    ans = [[0]*W for _ in range(H)]
    dx = [-1,0,1]
    dy = [-1,0,1]
    for i in range(H):
        for j in range(W):
            if S[i][j]=='#':
                ans[i][j] = '#'
                for x in dx:
                    for y in dy:
                        ny = i + y
                        nx = j + x
                        if 0<=nx<W and 0<=ny<H and ans[ny][nx]!='#':
                            ans[ny][nx] += 1
    for i in range(H):
        print(''.join(map(str,ans[i])))



if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
s=[input() for _ 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(h):
    for j in range(w):
        if s[i][j]=="#":
            continue

        num=0
        for d in range(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]=="#":
                num+=1

        list1=list(s[i])
        list1[j]=str(num)
        s[i]="".join(list1)
for i in range(h):
    print(s[i])

Submission status: Accepted

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

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

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

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
s = [list(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] = '#'
            if i > 0 and j > 0 and ans[i-1][j-1] != '#':
                ans[i-1][j-1] += 1
            if i > 0 and ans[i-1][j] != '#':
                ans[i-1][j] += 1
            if i > 0 and j < w-1 and ans[i-1][j+1] != '#':
                ans[i-1][j+1] += 1
            if j > 0 and ans[i][j-1] != '#':
                ans[i][j-1] += 1
            if j < w-1 and ans[i][j+1] != '#':
                ans[i][j+1] += 1
            if i < h-1 and j > 0 and ans[i+1][j-1] != '#':
                ans[i+1][j-1] += 1
            if i < h-1 and ans[i+1][j] != '#':
                ans[i+1][j] += 1
            if i < h-1 and j < w-1 and ans[i+1][j+1] != '#':
                ans[i+1][j+1] += 1

for k in range(h):
    for m in range(w):
        print(str(ans[k][m]), end='')
    print()

Submission status: Accepted

Solution code:
# ABC075 B-Minesweeper
import numpy as np

H, W = map(int, input().split())
s = np.zeros((H+2, W+2))

for i in range(H):
    S = input()
    for j, v in enumerate(S):
        if v == '#':
            s[i+1, j+1] = 1

for i in range(H):
    ans = ''
    for j in range(W):
        if s[i+1, j+1] == 1:
            ans += '#'
        else:
            ans += str(np.sum(s[i:i+3, j:j+3], dtype=np.int))
    print(ans)

Submission status: Accepted

Solution code:
def count(s,n,i,j):
    if s[i][j]=='#':
        n[i][j]='#'
    else:
        count=0
        for a in range(3):
            for b in range(3):
                if (0<=i-1+a<=h-1)and(0<=j-1+b<=w-1):
                    if s[i-1+a][j-1+b]=='#':
                        count+=1
        n[i][j]=str(count)


h,w=map(int,input().split())
s=[]
for i in range(h):
    s.append(list(input()))
n=s
for i in range(h):
    for j in range(w):
        count(s,n,i,j)
for i in range(h):
    print(''.join(s[i]))

Submission status: Accepted

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

dd=[[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]]
def check(i,j):
    ret=0
    for d in dd:
        x,y=d
        if 0<=i+x<h and 0<=j+y<w:
            if l[i+x][j+y]=="#":
                ret+=1
    return ret

for i in range(h):
    row=[]
    for j in range(w):
        if l[i][j]=="#":
            row.append("#")
        else:
            ret = check(i,j)
            row.append(ret)
    print(*row,sep="")

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
mine=[]
mine2=[['_']*(w+2)]
for i in range(h):
  s=input()
  line=[]
  for i in s:
    line.append(i)
  mine.append(line)
  line=['_']+line+['_']
  mine2.append(line)
mine2.append(['_']*(w+2))
#print(mine2)
num=[[0 for i in range(w)]for j in range(h)]
for i in range(1,h+1):
  for j in range(1,w+1):
    count=0
    if mine2[i][j]=='.':
      for a in range(-1,2):
        for b in range(-1,2):
          if mine2[i+a][j+b]=='#':
            count+=1
    num[i-1][j-1]=count
for i in range(h):
  for j in range(w):
    if mine[i][j]=='#':
      print('#',end='')
    else:
      print(num[i][j],end='')
  print()

Submission status: Accepted

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

vector = [[1,0],[0,1],[-1,0],[0,-1],[1,1],[-1,-1],[1,-1],[-1,1]]

for y in range(H):
    tmp = ""
    for x in range(W):
        ##print(y,x)
        if S[y][x] == "#":
            tmp += "#"
        else:
            cnt = 0
            for s,t in vector:
                dx = x + s
                dy = y + t
                if 0 <= dx <= W-1 and 0 <= dy <= H-1:
                    if S[dy][dx] == "#":
                        cnt += 1
            tmp += str(cnt)
    print(tmp)

Submission status: Accepted

Solution code:
data = input().split(' ')
h = int(data[0])
w = int(data[1])
s_mat = list()
for _ in range(h):
    s_mat.append(input())
# Count bombs
num_mat = [[0 for _ in range(w)] for _ in range(h)]
for hh in range(h):
    for ww in range(w):
        if s_mat[hh][ww] != '#':
            continue
        # if current cell has a bomb
        if hh + 1 <= h - 1 and ww + 1 <= w - 1:
            num_mat[hh + 1][ww + 1] += 1
        if hh + 1 <= h - 1:
            num_mat[hh + 1][ww] += 1
        if hh + 1 <= h - 1 and ww - 1 >= 0:
            num_mat[hh + 1][ww - 1] += 1
        if ww + 1 <= w - 1:
            num_mat[hh][ww + 1] += 1
        if ww - 1 >= 0:
            num_mat[hh][ww - 1] += 1
        if hh - 1 >= 0 and ww + 1 <= w - 1:
            num_mat[hh - 1][ww + 1] += 1
        if hh - 1 >= 0:
            num_mat[hh - 1][ww] += 1
        if hh - 1 >= 0 and ww - 1 >= 0:
            num_mat[hh - 1][ww - 1] += 1
# print
def get_cell(hh, ww):
    if s_mat[hh][ww] == '#':
        return '#'
    else:
        return str(num_mat[hh][ww])
for hh in range(h):
    print(''.join([get_cell(hh, ww) for ww in range(w)]))

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
s = [input() for _ in range(h)]
dx = [1, 1, 0, -1, -1, -1, 0, 1]
dy = [0, 1, 1, 1, 0, -1, -1, -1]
for i in range(h):
    s[i] = list(s[i])
    l = ""
    for j in range(w):
        if s[i][j] == "#":
            continue
        cnt = 0
        for k in range(8):
            ii = i + dx[k]
            jj = j + dy[k]
            if ii < 0 or ii > h - 1:
                continue
            elif jj < 0 or jj > w - 1:
                continue
            elif s[ii][jj] == "#":
                cnt += 1
        s[i][j] = str(cnt)
    l = "".join(s[i])
    print(l)

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
S=[list(input()) for i in range(H)]
T=[[None]*W for _ in range(H)]
for i in range(H):
    for j in range(W):
        if S[i][j]==".":
            tmp=0
            for k in range(j-1,j+2):
                if 0<=i-1<=H-1 and 0<=k<=W-1 and S[i-1][k]=="#":
                    tmp+=1
                if 0<=i+1<=H-1 and 0<=k<=W-1 and S[i+1][k]=="#":
                    tmp+=1
                if 0<=i<=H-1 and 0<=k<=W-1 and k!=j and S[i][k]=="#":
                    tmp+=1
            T[i][j]=tmp
        else:
            T[i][j]="#"
for i in range(H):
    for j in range(W):
        print(T[i][j],end="")
    print("\n")

Submission status: Accepted

Solution code:
def func(x,y):
    global s,h,w
    d = [-1,0,1]
    rv = 0
    for i in d:
        for j in d:
            if i == 0 and j == 0:
                continue
            if x+i >= 0 and x+i < h and y+j >= 0 and y+j < w:
                if s[x+i][y+j] == "#":
                    rv += 1
    return str(rv)

h,w = map(int,input().split())
s = [input() for _ in range(h)]
for i in range(h):
    ans = ""
    for j in range(w):
        if s[i][j] == ".":
            ans += func(i,j)
        else:
            ans += "#"
    print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys
import heapq
import re
from itertools import permutations
from bisect import bisect_left, bisect_right
from collections import Counter, deque
from fractions import gcd
from math import factorial, sqrt, ceil
from functools import lru_cache, reduce
INF = 1 << 60
MOD = 1000000007
sys.setrecursionlimit(10 ** 7)

# UnionFind
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

# ダイクストラ
def dijkstra_heap(s, edge, n):
    #始点sから各頂点への最短距離
    d = [10**20] * n
    used = [True] * n #True:未確定
    d[s] = 0
    used[s] = False
    edgelist = []
    for a,b in edge[s]:
        heapq.heappush(edgelist,a*(10**6)+b)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        #まだ使われてない頂点の中から最小の距離のものを探す
        if not used[minedge%(10**6)]:
            continue
        v = minedge%(10**6)
        d[v] = minedge//(10**6)
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,(e[0]+d[v])*(10**6)+e[1])
    return d

# 素因数分解
def factorization(n):
    arr = []
    temp = n
    for i in range(2, int(-(-n**0.5//1))+1):
        if temp%i==0:
            cnt=0
            while temp%i==0:
                cnt+=1
                temp //= i
            arr.append([i, cnt])

    if temp!=1:
        arr.append([temp, 1])

    if arr==[]:
        arr.append([n, 1])

    return arr

# 2数の最小公倍数
def lcm(x, y):
    return (x * y) // gcd(x, y)

# リストの要素の最小公倍数
def lcm_list(numbers):
    return reduce(lcm, numbers, 1)

# リストの要素の最大公約数
def gcd_list(numbers):
    return reduce(gcd, numbers)

# 素数判定
def is_prime(n):
    if n <= 1:
        return False
    p = 2
    while True:
        if p ** 2 > n:
            break
        if n % p == 0:
            return False
        p += 1
    return True


# limit以下の素数を列挙
def eratosthenes(limit):
    A = [i for i in range(2, limit+1)]
    P = []

    while True:
        prime = min(A)
        
        if prime > sqrt(limit):
            break
            
        P.append(prime)
            
        i = 0
        while i < len(A):
            if A[i] % prime == 0:
                A.pop(i)
                continue
            i += 1
            
    for a in A:
        P.append(a)
            
    return P

# 同じものを含む順列
def permutation_with_duplicates(L):

    if L == []:
        return [[]]

    else:
        ret = []

        # set（集合）型で重複を削除、ソート
        S = sorted(set(L))

        for i in S:

            data = L[:]
            data.remove(i)

            for j in permutation_with_duplicates(data):
                ret.append([i] + j)

        return ret


# ここから書き始める
h, w = map(int, input().split())
ans = [[] for i in range(h)]
for i in range(h):
    ans[i] = [j if j == "#" else "0" for j in input()]
# print(ans)
x = [-1, 0, 1]  
for i in range(h):
    for j in range(w):
        if ans[i][j] == "#":
            continue
        for k in x:
            for l in x:
                if 0 <= i + k < h and 0 <= j + l < w:
                    if ans[i + k][j + l] == "#":
                        # print(int(ans[i][j]) + 1)
                        ans[i][j] = str(int(ans[i][j]) + 1)
# print(ans)
for i in ans:
    print("".join(i))

Submission status: Accepted

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

S.append('.' *(W+2))

#print(S)
for h in range(1,H+1):
    ans = ''
    for w in range(1,W+1):
        c = 0
        if S[h][w] == '#':
            ans += '#'
        else:
            c += S[h-1][w-1:w+2].count('#')
            c += S[h][w-1:w+2].count('#')
            c += S[h+1][w-1:w+2].count('#')
            ans += str(c)
    print(ans)

Submission status: Accepted

Solution code:
import sys

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

def minesweeper(x, y):
    count = 0
    if S[x][y] == ".":
        for i in dx:
            for j in dy:
                nx = x + i
                ny = y + j
                if 0 <= nx < H and 0 <= ny < W and S[nx][ny] == "#":
                    count += 1
        S[x][y] = count
    if y + 1 != W:
        print(S[x][y], end="")
    else:
        print(S[x][y], end="\n")
        

H, W = map(int, sys.stdin.readline().split())
S = [list(sys.stdin.readline().rstrip()) for i in range(H)]

for i in range(H):
    for j in range(W):
        minesweeper(i, j)

Submission status: Accepted

Solution code:
# ABC075B

import numpy as np

h, w = map(int, input().split())
board = np.reshape(np.array(np.repeat("@", (h+2)*(w+2))), (h+2, w+2))
for i in range(h):
    s = input()
    board[i+1, 1:w+1] = np.array(list(s))
for i in range(1, h+1):
    count = np.zeros(w, dtype=str)
    for j in range(1, w+1):
        if board[i,j] == '.':
            count[j-1] = str(\
                (board[i-1, j-1] == "#") + (board[i-1, j] == "#") + (board[i-1, j+1] == "#") +\
                (board[i  , j-1] == "#") + (board[i  , j] == "#") + (board[i  , j+1] == "#") +\
                (board[i+1, j-1] == "#") + (board[i+1, j] == "#") + (board[i+1, j+1] == "#"))
        elif board[i, j] == "#":
            count[j-1] = "#"
    print(''.join(count))

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
s=[input() for _ in range(h)]
for i in range(h):
    ss = ''
    for j in range(w):
        if s[i][j] == '#':
            ss += '#'
        else:
            counter = 0
            for k in [-1, 0, 1]:
                for l in [-1, 0, 1]:
                    if 0 <= i+k <= h-1 and 0 <= j+l <= w-1 and s[i+k][j+l] == '#':
                        counter += 1
            ss += str(counter)
    print(ss)

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
S = [list(input()) for i in range(H)]
for i in range(H):
  for j in range(W):
    if S[i][j]=='.':
      count=0
      if i>0 and S[i-1][j]=='#': count+=1
      if (i>0 and j>0)and S[i-1][j-1]=='#': count+=1
      if (i>0 and j<W-1)and S[i-1][j+1]=='#': count+=1
      if i<H-1 and S[i+1][j]=='#': count+=1
      if (i<H-1 and j>0)and S[i+1][j-1]=='#': count+=1
      if (i<H-1 and j<W-1)and S[i+1][j+1]=='#': count+=1
      if j>0 and S[i][j-1]=='#': count+=1
      if j<W-1 and S[i][j+1]=='#': count+=1
      S[i][j]=str(count)
for i in range(H):
  for j in range(W):
    if j<W-1: print(S[i][j],end='')
    else: print(S[i][j])

Submission status: Accepted

Solution code:
H,W=map(int, input().split())
one = ""
for i in range(W+2):
  one = one + "."
S_map = [one]
for i in range(H):
  s = str(input())
  S_map.append("."+s+".")
S_map.append(one)

for i in range(1,1+H):
  count = ""
  for k in range(1,1+W):
    if S_map[i][k] == "#":
      count = count + "#"
    else:
      check_map=S_map[i-1][k-1:k+2]+S_map[i+1][k-1:k+2]
      check_map=check_map+S_map[i][k-1]+S_map[i][k+1]
      count = count + str(len([1 for check in check_map if check=="#"]))
  print(count)

Submission status: Accepted

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

Submission status: Accepted

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

for i in range(h):
    for j in range(w):
        if grid[i][j] != "#":
            min_i = 0 if i == 0 else i - 1
            max_i = h if i == h - 1 else i + 2
            min_j = 0 if j == 0 else j - 1
            max_j = w if j == w - 1 else j + 2
            filter = sum(list(g[min_j: max_j] for g in grid[min_i: max_i]), [])

            grid[i][j] = str(filter.count("#"))

for g in grid:
    print("".join(g))

Submission status: Accepted

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

import sys
import math
import heapq
mod=10**9+7
inf=float("inf")
from math import sqrt
from collections import deque
from collections import Counter
from math import ceil
input=lambda: sys.stdin.readline().strip()
sys.setrecursionlimit(11451419)
from functools import lru_cache
#メモ化再帰defの冒頭に毎回 @lru_cache(maxsize=10**10)
#引数にlistはだめ
#######ここまでテンプレ#######
#ソート、"a"+"b"、再帰ならPython3の方がいい
#######ここから天ぷら########

def a(x,y,a,b):
    if A[x][y]=="#" : ans[a][b]+=1
ans=[[0 for i in range(w)] for i in range(h)]
for i in range(h):
    for j in range(w):
        
        if A[i][j]=="#" : 
            ans[i][j]="#" 
            continue
        else:
          
            if i!=0 and j!=0 : a(i-1,j-1,i,j)
            if i!=0 : a(i-1,j,i,j)
            if i!=0 and j!=w-1 : a(i-1,j+1,i,j)
            if j!=0 : a(i,j-1,i,j)
            if j!=w-1 : a(i,j+1,i,j)
            if i!=h-1 and j!=0 : a(i+1,j-1,i,j)
            if i!=h-1 : a(i+1,j,i,j)
            if i!=h-1 and j!=w-1 : a(i+1,j+1,i,j)

for i in range(h):
    for j in range(w):
        ans[i][j]=str(ans[i][j])
for i in range(h):
    print("".join(ans[i]))

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
S = [input() for _ in range(H)]
ad = ['.' for _ in range(W)]
S.append(ad)
S.insert(0, ad)
newS = [['#' for _ in range(W)] for _ in range(H)]
for i in range(1, H+1):
    for j in range(W):
        if S[i][j] == '.':
            c = max(0, j-1)
            d = min(W-1, j+1)
            cnt = S[i][c:d+1].count('#')
            cnt += S[i-1][c:d+1].count('#')
            cnt += S[i+1][c:d+1].count('#')
            newS[i-1][j] = str(cnt)
for i in newS:
    print(''.join(i))

Submission status: Accepted

Solution code:
h,w = map(int,input().split())
l=[]
for i in range(h):
  s = list(input())
  l.append(s)
for i in range(h):
  for j in range(w):
    kazu = 0
    if l[i][j] == '.':
      if j != 0 and l[i][j-1] == '#':
        kazu += 1
      if j != w-1 and l[i][j+1] == '#':
        kazu += 1
      if i != 0 and l[i-1][j]== '#':
        kazu += 1
      if i != h-1 and l[i+1][j] == '#':
        kazu += 1
      if i >= 1 and j >= 1 and l[i-1][j-1] == '#':
        kazu += 1
      if i >= 1 and j <= w-2 and l[i-1][j+1] == '#':
        kazu += 1
      if i <= h-2 and j >= 1 and l[i+1][j-1] == '#':
        kazu += 1
      if i <= h-2 and j <= w-2 and l[i+1][j+1] == '#':
        kazu += 1
      l[i][j] = str(kazu)
for i in range(h):
  print(''.join(l[i]))

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

for hi in range(h):
    for wi in range(w):
        if sl[hi][wi]=="#":
            continue
        c = 0
        for dh in range(-1,2):
            for dw in range(-1,2):
                if h>hi+dh>=0 and w>wi+dw>=0:
                    if sl[hi+dh][wi+dw]=="#":
                        c += 1
        sl[hi][wi] = str(c)

for l in sl:
    print("".join(l))

Submission status: Accepted

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

for h in range(H):
    for w in range(W):
        if a[h][w] == ".":
            count = 0
            if h > 0:
                if w > 0:
                    if a[h - 1][w - 1] == "#":
                        count += 1
                if a[h - 1][w] == "#":
                    count += 1
                if w < W - 1:
                    if a[h - 1][w + 1] == "#":
                        count += 1
            if w > 0:
                if a[h][w - 1] == "#":
                    count += 1
            if w < W - 1:
                if a[h][w + 1] == "#":
                    count += 1
            if h < H - 1:
                if w > 0:
                    if a[h + 1][w - 1] == "#":
                        count += 1
                if a[h + 1][w] == "#":
                    count += 1
                if w < W - 1:
                    if a[h + 1][w + 1] == "#":
                        count += 1
            a[h][w] = str(count)
for h2 in range(H):
    print("".join(a[h2]))