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:
#!/usr/bin/env python3
import sys

def count(h, w, S: "List[str]") -> int:
    return (S[h-1][w] + S[h][w-1] + S[h-1][w-1] + S[h+1][w-1] + S[h-1][w+1] + S[h+1][w+1] + S[h+1][w] + S[h][w+1]).count("#")

def solve(H: int, W: int, S: "List[str]"):
    S = ["." * W] + S + ["." * W]
    for h in range(H+2):
        S[h] = "." + S[h] + "."
    ans = ["" for _ in range(H)]
    for h in range(H):
        for w in range(W):
            if S[h+1][w+1] != "#":
                ans[h] += str(count(h+1, w+1, S))
            else:
                ans[h] += "#"
    for a in ans:
        print("".join(a))
    return


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    H = int(next(tokens))  # type: int
    W = int(next(tokens))  # type: int
    S = [next(tokens) for _ in range(H)]  # type: "List[str]"
    solve(H, W, S)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# coding: utf-8
import re
import math
from collections import defaultdict
import itertools
from copy import deepcopy
import random
from heapq import heappop,heappush
import time
import os
import queue
import sys
import datetime
from functools import lru_cache
#@lru_cache(maxsize=None)
readline=sys.stdin.readline
sys.setrecursionlimit(2000000)
#import numpy as np
alphabet="abcdefghijklmnopqrstuvwxyz"
mod=int(10**9+7)
inf=int(10**20)
def yn(b):
    if b:
        print("yes")
    else:
        print("no")
def Yn(b):
    if b:
        print("Yes")
    else:
        print("No")
def YN(b):
    if b:
        print("YES")
    else:
        print("NO")
class union_find():
    def __init__(self,n):
        self.n=n
        self.P=[a for a in range(N)]
        self.rank=[0]*n
 
    def find(self,x):
        if(x!=self.P[x]):self.P[x]=self.find(self.P[x])
        return self.P[x]
 
    def same(self,x,y):
        return self.find(x)==self.find(y)
 
    def link(self,x,y):
        if self.rank[x]<self.rank[y]:
            self.P[x]=y
        elif self.rank[y]<self.rank[x]:
            self.P[y]=x
        else:
            self.P[x]=y
            self.rank[y]+=1
 
    def unite(self,x,y):
        self.link(self.find(x),self.find(y))
 
    def size(self):
        S=set()
        for a in range(self.n):
            S.add(self.find(a))
        return len(S)
def is_power(a,b):#aはbの累乗数か
    now=b
    while now<a:
        now*=b
    if now==a:return True
    else:return False
def bin_(num,size):
    A=[0]*size
    for a in range(size):
        if (num>>(size-a-1))&1==1:
            A[a]=1
        else:
            A[a]=0
    return A
def get_facs(n,mod_=0):
    A=[1]*(n+1)
    for a in range(2,len(A)):
        A[a]=A[a-1]*a
        if(mod>0):A[a]%=mod_
    return A
def comb(n,r,mod,fac):
    if(n-r<0):return 0
    return (fac[n]*pow(fac[n-r],mod-2,mod)*pow(fac[r],mod-2,mod))%mod
def next_comb(num,size):
    x=num&(-num)
    y=num+x
    z=num&(~y)
    z//=x
    z=z>>1
    num=(y|z)
    if(num>=(1<<size)):return False
    else:
        return num
def get_primes(n,type="int"):
    A=[True]*(n+1)
    A[0]=False
    A[1]=False
    for a in range(2,n+1):
        if A[a]:
            for b in range(a*2,n+1,a):
                A[b]=False
    if(type=="bool"):return A
    B=[]
    for a in range(n+1):
        if(A[a]):B.append(a)
    return B
def is_prime(num):
    if(num<=2):return False
    i=2
    while i*i<=num:
       if(num%i==0):return False
       i+=1
    return True
def ifelse(a,b,c):
    if a:return b
    else:return  c
def join(A,c=" "):
    n=len(A)
    A=list(map(str,A))
    s=""
    for a in range(n):
        s+=A[a]
        if(a<n-1):s+=c
    return s
def factorize(n,type_="dict"):
    b = 2
    list_ = []
    while b * b <= n:
        while n % b == 0:
            n //= b
            list_.append(b)
        b+=1
    if n > 1:list_.append(n)
    if type_=="dict":
        dic={}
        for a in list_:
            if a in dic:
                dic[a]+=1
            else:
                dic[a]=1
        return dic
    elif type_=="list":
        return list_
    else:
        return None
def floor_(n,x=1):
    return x*(n//x)
def ceil_(n,x=1):
    return x*((n+x-1)//x)
def hani(x,min_,max_):
    ret=x
    if x<min_:ret=min_
    if x>max_:ret=max_
    return ret
def seifu(x):
    return x//abs(x)
###################################################

def main():
    H,W=map(int,input().split())
    S=[]
    for a in range(H):
        S.append(input())
    ans=[["a" for a in range(W)] for b in range(H)]
    for h in range(H):
        for w in range(W):
            if S[h][w]=="#":
                ans[h][w]="#"
            else:
                count=0
                for a in range(-1,2):
                    for b in range(-1,2):
                        x=w+b
                        y=h+a
                        
                        if 0<=y and y<H and 0<=x and x<W:
                            if S[y][x]=="#":
                                count+=1
                ans[h][w]=str(count)
    for a in range(H):
        print("".join(ans[a]))
main()

Submission status: Accepted

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

s = [[""]*w for _ in range(h)]

# python, list(文字列)とすれば1文字ずつを要素とするlistができる
# 別に文字列のまま扱ってもよさそう
for i in range(h):
    s[i] = list(temp[i])

ns = [[0]*w for _ in range(h)]

# 文字列がタプル同様あとから変更できない仕様に悩まされた
# 文字列として受け取るのではなく，リストで最初から受け取ればよい

# なんでこれリストnsがまとめて書き換わってしまうんだ
# -> https://note.nkmk.me/python-list-initialize/
  # 要素のリストがすべて同じオブジェクトになってしまっているらしい
  # s, nsを内包表記で書く必要がある
for i in range(h):
    for j in range(w):
        if s[i][j] == "#":
            ns[i][j] = "#"

for i in range(h):
    for j in range(w):
        if s[i][j] == "#":
            
            if i != 0:
                if ns[i-1][j] != "#": ns[i-1][j] += 1
                if j != 0:
                    if ns[i-1][j-1] != "#": ns[i-1][j-1] += 1
                if j != w-1:
                    if ns[i-1][j+1] != "#": ns[i-1][j+1] += 1
                
            if j != 0:
                if ns[i][j-1] != "#": ns[i][j-1] += 1
            if j != w-1:
                if ns[i][j+1] != "#": ns[i][j+1] += 1

            if i != h-1:
                if ns[i+1][j] != "#": ns[i+1][j] += 1
                if j != 0:
                    if ns[i+1][j-1] != "#": ns[i+1][j-1] += 1
                if j != w-1:
                    if ns[i+1][j+1] != "#": ns[i+1][j+1] += 1

for i in range(h):
    for j in range(w):
        ns[i][j] = str(ns[i][j])

for i in range(h):
    print("".join(ns[i]))

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
S = [list(input()) for _ in range(H)]
dx = [0, 1, 0, -1, 1, 1, -1, -1]
dy = [1, 0, -1, 0, 1, -1, 1, -1]
for i in range(H):
    for j in range(W):
        if S[i][j] != '#':
            S[i][j] = 0
            for x, y in zip(dx, dy):
                ni = i + x
                nj = j + y
                if 0 <= ni < H and 0 <= nj < W:
                    if S[ni][nj] == '#':
                        S[i][j] += 1
for i in range(H):
    for j in range(W):
        if j + 1 != W:
            print(S[i][j], end='')
        else:
            print(S[i][j])

Submission status: Accepted

Solution code:
N, M = map(int,input().split()) 
P= [["." for _ in range(M+2)] for i in range(N+2)]

for i in range(1,N+1):
    P[i][1:M+1] = list(input())


def rep(a,b):#aたて
    ans = 0
    for i in range(-1,2,1):
        for j in range(-1,2,1):
            if P[a+i][b+j]=="#":
                ans += 1
    P[a][b] = ans


for i in range(1,M+1):
    for j in range(1,N+1):
        if P[j][i] == ".":
          rep(j,i)

for i in range(1,N+1):
    print(''.join([str(i) for i in P[i][1:M+1]]))

Submission status: Accepted

Solution code:
import numpy as np

H, W = map(int, input().split())
S = [list(input()) for _ in range(H)]
  
dx = [1, 1,  1, 0,  0, -1, -1, -1]
dy = [1, 0, -1, 1, -1,  1,  0, -1]

for h, row in enumerate(S):
  for w, i in enumerate(row):
    if i == '.':
      S[h][w] = 0
    if i == '#':
      for x, y in zip(dx, dy):
        if 0 <= x+w < W and 0 <= y+h < H:
          if S[y+h][x+w] == '#':
            continue
          elif S[y+h][x+w] == '.':
            S[y+h][x+w] = 1
          else:
            S[y+h][x+w] += 1
            
for s in S:
  print(''.join(map(str, s)))

Submission status: Accepted

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

def resolve():
	h, w = map(int, input().split())
	m = [[0]*w for _ in range(h)]
	s = [list(input()) for _ in range(h)]
	for i in range(h):
		for j in range(w):
			if s[i][j] == '#':
				m[i][j] = '#'
				continue
			for k in range(8):
				ny = i + dy[k]
				nx = j + dx[k]
				if 0 <= ny < h and 0 <= nx < w and s[ny][nx] == '#':
					m[i][j] += 1
	for seq in m:
		print("".join([str(i) for i in seq]))
resolve()

Submission status: Accepted

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

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

dxy = [(-1,-1),(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1)]
for y in range(H):
    for x in range(W):
        if ans[y][x] == '#': continue
        c = 0
        for dx,dy in dxy:
            if x+dx < 0 or x+dx > W-1 or y+dy < 0 or y+dy > H-1: continue
            if ans[y+dy][x+dx] == '#': c += 1
        ans[y][x] = c

for row in ans:
    print("".join(list(map(str,row))))

Submission status: Accepted

Solution code:
H,W = map(int, input().split())
s =[]
s_w =[]

m = []

for i in range(H):
    s_t = input()
    s_w =[]
    for j in range(W):           
        s_w.append(s_t[j])
    s.append(s_w)

#print(s)

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

for i in range(H):
    for j in range(W):
        if s[i][j] == "#":
            continue
        
        count = 0
        for k in range(8):
            
            ni = i + dy[k]
            nj = j + dx[k]
            
            if (ni<0 or H<=ni) or (nj<0 or W<=nj):
                continue
            if s[ni][nj] == "#":
                count += 1
        s[i][j] = str(count)

for i in range(H):
    for j in range(W):
        print(s[i][j], end="")
    print()

Submission status: Accepted

Solution code:
import numpy as np
H,W = map(int,input().split())
table = [["."]*(W+2),]
for _ in range(H):
    table.append([".",]+list(input())+[".",])
table.append(["."]*(W+2))
table = np.array(table)
ans = []
#print(table)
for h in range(H):
    for w in range(W):
        mawari = table[h:h+3,w:w+3]
        #print(mawari)
        if mawari[1,1] == ".":
            ans.append(np.count_nonzero(mawari=="#"))
        else:
            ans.append("#")
ans = np.array(ans).reshape(H,W).astype(np.unicode)
for i in ans:
    print("".join(i))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil,sqrt
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7
#s=input().rstrip()

h,w=MI()
mines=[[0 for i in range(w+2)]for i in range(h+2)]

for i in range(w+2):
    mines[0][i]="."
    mines[h+1][i]="."
for i in range(h+2):
    mines[i][0]="."
    mines[i][w+1]="."
for i in range(h):
    s=list(input().rstrip())
    for j in range(w):
        mines[i+1][j+1]=s[j]
#print(mines)
minum=[[0 for i in range(w+2)]for i in range(h+2)]
for i in range(1,h+1):
    for j in range(1,w+1):
        if mines[i][j]=="#":
            minum[i-1][j]+=1
            minum[i+1][j]+=1
            minum[i][j+1]+=1
            minum[i][j-1]+=1
            minum[i+1][j+1]+=1
            minum[i+1][j-1]+=1
            minum[i-1][j+1]+=1
            minum[i-1][j-1]+=1
#print(minum)
for i in range(1,h+1):
    for j in range(1,w+1):
        if mines[i][j]=="#":
            print("#",end="")
        else:
            print(minum[i][j],end="")
    print()

Submission status: Accepted

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

Submission status: Accepted

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

s = []

for i in range(h):
    s += [str(input())]
    
    

def padding(s,h,w):
    res = []
    res_0 = '.'*(w+2)
    for i in range(h+2):
        if i ==0:
            res = res + [res_0]
        elif i == h+1:
            res = res + [res_0]
        else:
            res_add = '.' + s[i-1] + '.'
            res += [res_add]
    return res

def check_mine(s,i,j):
    cout = 0
    for k in [-1+i,i,1+i]:
        for l in [-1+j,j,1+j]:
            if s[k][l] == '#':
                cout +=1
                
    if s[i][j] == '.':
        return str(cout)
    else:
        return '#'
    
s = padding(s,h,w)

for i in range(h):
    temp = str()
    for j in range(w):
        temp += check_mine(s,i+1,j+1)
    print(temp)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
H, W = map(int,input().split())
s = [input() for _ in range(H)]
for h in range(H):
    l = ""
    for w in range(W):
        l += "#" if s[h][w] == "#" else str(
                    sum(
                        [t[max(0, w - 1) : min(W, w + 2)]
                            .count("#") for t in 
                         s[max(0, h - 1) : min(H, h + 2)]
                        ]
                        ))
    print(l)

Submission status: Accepted

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

pad_S = [['.']*(W+2)] + [['.']+s+['.'] for s in S] + [['.']*(W+2)]

def calc_bomb(r, c, pad_S):
    h = pad_S[r-1][c-1:c+2].count('#')
    m = pad_S[r][c-1:c+2].count('#')
    l = pad_S[r+1][c-1:c+2].count('#')
    return h+m+l

for i, s in enumerate(S):
   r = i+1 
   lis = []
   for k, char in enumerate(s):
       c = k+1
       if char == '#':
           lis.append('#')
       else:
           lis.append(str(calc_bomb(r, c, pad_S)))
   print(''.join(lis))

Submission status: Accepted

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

for i in range(h):
    for j in range(w):
        if s[i][j] == '.':
            s[i][j] = 0
        print(s[i][j], end='')  # 改行せずにprint
    print()

Submission status: Accepted

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

        else:
            continue

for i in range(h):
    for j in range(w):
        if s[i][j] == '.':
            s[i][j] = 0
        print(s[i][j], end='')  # 改行せずにprint
    print()

Submission status: Accepted

Solution code:
# A
h, w = map(int, input().split())
s = [list(input()) for _ in range(h)]#(h,w)
mine=[[0 for i in range(w)]for j in range(h)]
# 8方向
# #(-1,1)  #(0,1)  #(1,1)
# #(-1,0)    (#)   #(1,0)
# #(-1,-1) #(0,-1) #(1,-1)

dx = [0, 1, 1, 1, 0, -1, -1, -1]
dy = [-1, -1, 0, 1, 1, 1, 0, -1 ]
# print(s,mine)
for i in range(h):
    for j in range(w):
        # print(i,j)
        if s[i][j] == "#":
            mine[i][j]="#"
            for k in range(len(dx)):
                nx = i + dx[k]
                ny = j + dy[k]
                # print("m:",nx,ny)
                if 0 <= nx < h and 0 <= ny < w:
                    if s[nx][ny] != "#":
                        mine[nx][ny] += 1
for i in mine:
    print(*i,sep="")

Submission status: Accepted

Solution code:
import sys
## io ##
def IS(): return sys.stdin.readline().rstrip()
def II(): return int(IS())
def MII(): return list(map(int, IS().split()))
def MIIZ(): return list(map(lambda x: x-1, MII()))
## dp ##
def DD2(d1,d2,init=0): return [[init]*d2 for _ in range(d1)]
def DD3(d1,d2,d3,init=0): return [DD2(d2,d3,init) for _ in range(d1)]
## math ##
def to_bin(x: int) -> str: return format(x, 'b') # rev => int(res, 2)
def to_oct(x: int) -> str: return format(x, 'o') # rev => int(res, 8)
def to_hex(x: int) -> str: return format(x, 'x') # rev => int(res, 16)
MOD=10**9+7
def divc(x,y) -> int: return -(-x//y)
def divf(x,y) -> int: return x//y
def gcd(x,y):
    while y: x,y = y,x%y
    return x
def lcm(x,y): return x*y//gcd(x,y)
def enumerate_divs(n):
    """Return a tuple list of divisor of n"""
    return [(i,n//i) for i in range(1,int(n**0.5)+1) if n%i==0]
def get_primes(MAX_NUM=10**3):
    """Return a list of prime numbers n or less"""
    is_prime = [True]*(MAX_NUM+1)
    is_prime[0] = is_prime[1] = False
    for i in range(2, int(MAX_NUM**0.5)+1):
        if not is_prime[i]: continue
        for j in range(i*2, MAX_NUM+1, i):
            is_prime[j] = False
    return [i for i in range(MAX_NUM+1) if is_prime[i]]
## libs ##
from itertools import accumulate as acc, combinations as combi, product, combinations_with_replacement as combi_dup
from collections import deque, Counter
from heapq import heapify, heappop, heappush
from bisect import bisect_left
#======================================================#

def main():
    h, w = MII()
    s = ['.'*(w+2)]
    for i in range(h):
        s.append('.'+IS()+'.')
    s.append('.'*(w+2))
    ans = []
    for hi in range(1,h+1):
        tmp = ''
        for wi in range(1,w+1):
            if s[hi][wi] == '#':
                tmp += '#'
                continue
            cnt = 0
            cnt += sum([1 for c in s[hi-1][wi-1:wi+2] if c == '#'])
            cnt += sum([1 for c in s[hi][wi-1:wi+2] if c == '#'])
            cnt += sum([1 for c in s[hi+1][wi-1:wi+2] if c == '#'])
            tmp += str(cnt)
        ans.append(tmp)
    print(*ans, sep='\n')

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()))
for i in range(0,h):
  for j in range(0,w):
    if s[i][j]==".":
      count=0
      try:
        if s[i-1][j-1]=="#" and i-1!=-1 and j-1!=-1:
          count+=1
      except IndexError:
        pass
      try:
        if s[i-1][j]=="#" and i-1!=-1 and j!=-1:
          count+=1
      except IndexError:
        pass
      try:
        if s[i-1][j+1]=="#" and i-1!=-1 and j+1!=-1:
          count+=1
      except IndexError:
        pass
      try:
        if s[i][j-1]=="#" and i!=-1 and j-1!=-1:
          count+=1
      except IndexError:
        pass
      try:
        if s[i][j+1]=="#" and i!=-1 and j+1!=-1:
          count+=1
      except IndexError:
        pass
      try:
        if s[i+1][j-1]=="#" and i+1!=-1 and j-1!=-1:
          count+=1
      except IndexError:
        pass
      try:
        if s[i+1][j]=="#"and i+1!=-1 and j!=-1:
          count+=1
      except IndexError:
        pass
      try:
        if s[i+1][j+1]=="#"and i+1!=-1 and j+1!=-1:
          count+=1
      except IndexError:
        pass
      s[i][j]=count

for x in range(0,len(s)):
  for y in range(0,len(s[0])):
    if y!=len(s[0])-1:
      print(s[x][y],end="")
    else:
      print(s[x][y])

Submission status: Accepted

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

def count(x, y):
    cnt = 0
    for dx in range(-1, 2):
        for dy in range(-1, 2):
            if not (0<=x+dx<w and 0<=y+dy<h):
                continue
            if s[y+dy][x+dx]=='#':
                cnt += 1
    return str(cnt)

for i, row in enumerate(s):
    new_str = ''
    for j, e in enumerate(row):
        new_str += count(j, i) if e=='.' else '#'
    print(new_str)

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
board =list()
ans =list()
count = 0
for y in range(H):
  board.append (input())
  ans.append(["#"]*W)
for y in range(H):
  for x in range(W):
    if board[y][x] ==".":
      count = 0
      for y2 in range(y-1,y+2):
        for x2 in range(x-1,x+2):
          if y2<0 or y2>= H:
            continue
          elif x2<0 or x2>= W:
            continue
          else:
            if board[y2][x2] == "#":
              count += 1
      ans[y][x] = count
for y in range(H):
  for x in range(W):
    print(ans[y][x],end="")
  print()

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
lst = [input() for _ in range(H)]
res = [[0 for i in range(W)] for j in range(H)]
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 lst[i][j] == '#':
            res[i][j] = '#'
            for k in range(8):
                xk = i + x[k]
                yk = j + y[k]
                if 0<= xk < H and 0 <= yk < W:
                    if res[xk][yk] != '#':
                        res[xk][yk] += 1
for row in res:
    for i in row:
        print(i, end='')
    print('')

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
S=['.']*(W+2)
i=0
while i<H:
    S+=['.']+list(input())+['.']
    i+=1
S+=['.']*(W+2)

j=W+3
while j<=(W+2)*(H+1)-2:
    count=0
    if S[j]!='#':
        if S[j-(W+3)]=='#':
            count+=1
        if S[j-(W+2)]=='#':
            count+=1
        if S[j-(W+1)]=='#':
            count+=1
        if S[j-1]=='#':
            count+=1
        if S[j+1]=='#':
            count+=1
        if S[j+(W+1)]=='#':
            count+=1
        if S[j+(W+2)]=='#':
            count+=1
        if S[j+(W+3)]=='#':
            count+=1
        S[j]=str(count)
    j+=1

k=1
while k<=H:
    print(''.join(S[k*(W+2)+1:k*(W+2)+1+W]))
    k+=1

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
mapp = (['.' * (W + 2)]
        + ['.%s.' % input() for _ in range(H)]
        + ['.' * (W + 2)])

dh = [-1, -1, -1, 0, 0, 1, 1, 1]
dw = [-1, 0, 1, -1, 1, -1, 0, 1]
for h in range(1, H + 1):
    line = ''
    for w in range(1, W + 1):
        if mapp[h][w] == '#':
            line += '#'
            continue

        line += str(sum(mapp[h + dhi][w + dwi] == '#' for dhi, dwi in zip(dh, dw)))
    print(line)

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
mapp = ['.' * (W + 2)]
for _ in range(H):
    mapp += ['.%s.' % input()]
mapp += ['.' * (W + 2)]

dh = [-1, -1, -1, 0, 0, 1, 1, 1]
dw = [-1, 0, 1, -1, 1, -1, 0, 1]
for h in range(1, H + 1):
    line = ''
    for w in range(1, W + 1):
        if mapp[h][w] == '#':
            line += '#'
            continue

        line += str(sum(mapp[h + dhi][w + dwi] == '#' for dhi, dwi in zip(dh, dw)))
    print(line)

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
a = []
a.append(' ' * (w + 2))
for i in range(h):
    a.append(' ' + input() + ' ')
a.append(' ' * (w + 2))
ans = [[None for _ in range(w)] for _ in range(h)]
for i in range(1, h + 1):
    for j in range(1, w + 1):
        if a[i][j] == '#':
            ans[i - 1][j - 1] = '#'
        elif a[i][j] == '.':
            ans[i - 1][j - 1] = str(''.join(a[k][l] for k in range(i - 1, i + 2) for l in range(j - 1, j + 2)).count('#'))
for value in ans:
    print(''.join(value))

Submission status: Accepted

Solution code:
def main():
    H, W = map(int, input().split())
    S = [list(input()) for _ in range(H)]
    dx_dy = [[1, 0], [-1, 0], [0, 1], [0, -1], [1, -1], [1, 1], [-1, -1], [-1, 1]]
    ans = []
    for nx in range(H):
        l = ''
        for ny in range(W):
            if S[nx][ny] == '.':
                cnt = 0
                for i in range(8):
                    x, y = nx + dx_dy[i][0], ny + dx_dy[i][1]
                    if 0  <= x < H and 0 <= y < W:
                        if S[x][y] == '#':
                            cnt += 1
                l += str(cnt)
            else:
                l += '#'
        ans.append(l)
    for a in ans:
        print(a)
                            
    
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
import itertools
sys.setrecursionlimit(1000000000)
from heapq import heapify,heappop,heappush,heappushpop
import math
import collections

h,w = map(int,input().split())
g = []
for i in range(h):
    g.append(input())
c = [[0 for i in range(w)] for i in range(h)]
for i in range(h):
    for j in range(w):
        if g[i][j] == "#":
            if j < w - 1:
                c[i][j+1] += 1
            if j>0:
                c[i][j-1] += 1
            if i < h-1:
                c[i+1][j] += 1
            if i > 0:
                c[i-1][j] += 1
            if i>0 and j>0:
                c[i-1][j-1] += 1
            if i > 0 and j < w -1:
                c[i-1][j+1] += 1
            if i<h-1 and j>0:
                c[i+1][j-1] += 1
            if i < h-1 and j < w - 1:
                c[i+1][j+1] +=1
        if g[i][j] == ".":
            continue
for i in range(h):
    ans = ""
    for j in range(w):
        if g[i][j] == "#":
            ans += "#"
        else:
            ans += str(c[i][j])
    print(ans)

Submission status: Accepted

Solution code:
from itertools import product
H, W = list(map(int, input().split()))
S = [input() for _ in range(H)]
ans = S[:]
ans = [list(a) for a in ans]
S = ['.' * (W + 2)] + ['.' + s + '.' for s in S] + ['.' * (W + 2)]
for h, w in product(range(1, H + 1), range(1, W + 1)):
    if S[h][w] == '#':
        continue
    count = 0
    for i, j in product(range(h - 1, h + 2), range(w - 1, w + 2)):
        if (i == h) and (j == w):
            continue
        if S[i][j] == '#':
            count += 1
    ans[h - 1][w - 1] = str(count)
ans = [''.join(a) for a in ans]
[print(a) for a in ans]

Submission status: Accepted

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

h, w = map(int, input().split())
field = []

for _ in range(h):
  field.append(list(input()))
  
for y in range(h):
  for x in range(w):
    if field[y][x] == '#':
      continue
      
    ans = 0
      
    for tips in range(8):
      ny = y + dy[tips]
      nx = x + dx[tips]
        
      if ny < 0 or ny >= h or nx < 0 or nx >= w:
        continue
      
      if field[ny][nx] == '#':
        ans += 1
        
    field[y][x] = str(ans)
    
for y in range(h):
  print("".join(field[y]))

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
lst = [input() for _ in range(H)]
res = [[0 for i in range(W)] for j in range(H)]
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 lst[i][j] == '#':
            res[i][j] = '#'
            for k in range(8):
                xk = i + x[k]
                yk = j + y[k]
                if 0<= xk < H and 0 <= yk < W:
                    if res[xk][yk] != '#':
                        res[xk][yk] += 1
for row in res:
    for i in row:
        print(i, end='')
    print('')

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline


def read():
    H, W = map(int, input().strip().split())
    S = [['x' for j in range(W+2)] for i in range(H+2)]
    for i in range(H):
        s = input().strip()
        for j in range(W):
            S[i+1][j+1] = s[j]
    return H, W, S


def put_number(y, x, S):
    if S[y][x] == '#':
        return
    count = 0
    for dy, dx in [(1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1)]:
        ny, nx = dy + y, dx + x
        if S[ny][nx] == '#':
            count += 1
    S[y][x] = str(count)


def solve(H, W, S):
    for i in range(1, H+1):
        for j in range(1, W+1):
            put_number(i, j, S)
    for i in range(1, H+1):
        print(''.join(S[i][1:W+1]))


if __name__ == '__main__':
    inputs = read()
    outputs = solve(*inputs)
    if outputs is not None:
        print("%s" % str(outputs))