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):
    s.append("."+input()+".")
s.append("."*(w+2))

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

h += 2
w += 2

for i in range(1,h-1):
    for j in range(1,w-1):
        if s[i][j] == "#":
            li[i-1][j-1] = "#"
            continue
        point = 0
        x = [-1,0,1]
        y = [-1,0,1]
        for nx in x:
            for ny in y:
                if nx == 0 and ny == 0:
                    continue
                if s[i+nx][j+ny] == "#":
                    point += 1
        li[i-1][j-1] = point

for i in li:
    print(''.join(map(str,i)))

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
S = [input() for _ in range(H)]
newS = [[0 for _ in range(W)] for _ in range(H)]
for i in range(H):
    for j in range(W):
        if S[i][j] == '.':
            counter = 0
            for k in [-1,0,1]:
                for l in [-1,0,1]:
                    if 0 <= i+k < H and 0 <= j+l <W:
                        if S[i+k][j+l] == '#':
                            counter += 1
            newS[i][j] = counter
        else:
            newS[i][j] = '#'

for i in range(H):
    for j in range(W):
        print(newS[i][j], end='')
    print('\n',end='')

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
import math
from bisect import bisect_left
from bisect import bisect_right
import collections
import copy
import heapq
from collections import defaultdict
from heapq import heappop, heappush
import itertools
input = sys.stdin.readline
from collections import defaultdict
from heapq import heappop, heappush

from decimal import *

##### リストの 二分木検索 #####
# bisect_left(lists, 3)
# bisect_right(lists, 3)

##### プライオリティキュー #####
# heapq.heapify(a) #リストaのheap化
# heapq.heappush(a,x) #heap化されたリストaに要素xを追加
# heapq.heappop(a) #heap化されたリストaから最小値を削除＆その最小値を出力

# heapq.heappush(a, -x) #最大値を取り出す時は、pushする時にマイナスにして入れよう
# heapq.heappop(a) * (-1) #取り出す時は、-1を掛けて取り出すこと

##### タプルリストのソート #####
# sorted(ans) #(a, b) -> 1st : aの昇順, 2nd : bの昇順
# sorted(SP, key=lambda x:(x[0],-x[1])) #(a, b) -> 1st : aの昇順, 2nd : bの降順
# sorted(SP, key=lambda x:(-x[0],x[1])) #(a, b) -> 1st : aの降順, 2nd : bの昇順
# sorted(SP, key=lambda x:(-x[0],-x[1])) #(a, b) -> 1st : aの降順, 2nd : bの降順

# sorted(SP, key=lambda x:(x[1])) #(a, b) -> 1st : bの昇順
# sorted(SP, key=lambda x:(-x[1])) #(a, b) -> 1st : bの降順

##### 累乗 #####
# pow(x, y, z) -> x**y % z

##### 割り算の切り上げ #####
# tmp = -(-4 // 3)

##### dict の for文 #####
# for k, v in d.items():
#     print(k, v)

##### 進数の変換 #####
# bin_str = bin(i)[2:]
# oct_str = oct(i)[2:]
# hex_str = hex(i)[2:]

##### とても大きな数 と 小数の計算誤差 #####
# 「Decimal」は計算誤差を 0にできる。必要に応じて粒度を設定せよ。
# getcontext().prec = 100
#
# tmp = Decimal(i)
# A,B = map(Decimal, input().split())
# ans = A * B

def inputInt(): return int(input())
def inputMap(): return map(int, input().split())
def inputList(): return list(map(int, input().split()))
def inputStr(): return input()[:-1]

inf = float('inf')
mod = 1000000007

#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-

def main():
	H,W = inputMap()
	S = []
	for i in range(H):
		s = inputStr()
		S.append(s)

	comm = [(0,1), (0,-1), (1,0), (-1,0), (1,1), (1,-1), (-1,-1), (-1,1)]
	ans = []
	for i,val in enumerate(S):
		ans_lain = []
		for j,vol in enumerate(val):
			if vol == "#":
				ans_lain.append("#")
			else:
				tmp = 0
				for com in comm:
					x = i
					y = j
					do_x,do_y = com
					x = x + do_x
					y = y + do_y
					if x < 0 or x > H-1:
						continue
					if y < 0 or y > W-1:
						continue

					if S[x][y] == "#":
						tmp += 1
				ans_lain.append(str(tmp))
		ans.append(ans_lain)

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




#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
# 2分検索のリバース
def bisect_left_reverse(a, x):
    if a[0] <= x:
        return 0
    if x < a[-1]:
        return len(a)
    # 二分探索
    ok = len(a) - 1
    ng = 0
    while (abs(ok - ng) > 1):
        mid = (ok + ng) // 2
        if a[mid] <= x:
            ok = mid
        else:
            ng = mid
    return ok

def bisect_right_reverse(a, x):
    if a[0] < x:
        return 0
    if x <= a[-1]:
        return len(a)
    # 二分探索
    ok = len(a) - 1
    ng = 0
    while (abs(ok - ng) > 1):
        mid = (ok + ng) // 2
        if a[mid] < x:
            ok = mid
        else:
            ng = mid
    return ok

#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
# 2分検索
# 存在しない場合: None 存在する場合: その値
def binary_search(list, item):
    low = 0
    high = len(list) - 1

    while low <= high:
        mid = (low + high) //2
        guess = list[mid]
        if guess == item:
            return mid
        if guess > item:
            high = mid -1
        else:
            low = mid + 1
    return None

#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
# N 個のボールを K グループに分ける場合のパターン数
def sunuke(N, K, mod=10**9+7):
	if N < K or K-1 < 0:
		return 0
	else:
		return combination(N-1, K-1, mod)

#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
# nCr mod m
# rがn/2に近いと非常に重くなる
def combination(n, r, mod=10**9+7):
    r = min(r, n-r)
    res = 1
    for i in range(r):
        res = res * (n - i) * modinv(i+1, mod) % mod
    return res

# mを法とするaの乗法的逆元
def modinv(a, mod=10**9+7):
    return pow(a, mod-2, mod)

def egcd(a, b):
    if a == 0:
        return b, 0, 1
    else:
        g, y, x = egcd(b % a, a)
        return g, x - (b // a) * y, y

#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
# nHr mod m
# 問題によって、combination()を切り替えること
def H(n, r, mod=10**9+7):
	# comb = Combination(n+r-1, mod)
	# return comb(n+r-1, r)
    return combination(n+r-1, r, mod)


class Combination:
    """
    O(n)の前計算を1回行うことで，O(1)でnCr mod mを求められる
    n_max = 10**6のとき前処理は約950ms (PyPyなら約340ms, 10**7で約1800ms)
    使用例：
    comb = Combination(1000000)
    print(comb(5, 3))  # 10
    """
    def __init__(self, n_max, mod=10**9+7):
        self.mod = mod
        self.modinv = self.make_modinv_list(n_max)
        self.fac, self.facinv = self.make_factorial_list(n_max)

    def __call__(self, n, r):
        return self.fac[n] * self.facinv[r] % self.mod * self.facinv[n-r] % self.mod

    def make_factorial_list(self, n):
        # 階乗のリストと階乗のmod逆元のリストを返す O(n)
        # self.make_modinv_list()が先に実行されている必要がある
        fac = [1]
        facinv = [1]
        for i in range(1, n+1):
            fac.append(fac[i-1] * i % self.mod)
            facinv.append(facinv[i-1] * self.modinv[i] % self.mod)
        return fac, facinv

    def make_modinv_list(self, n):
        # 0からnまでのmod逆元のリストを返す O(n)
        modinv = [0] * (n+1)
        modinv[1] = 1
        for i in range(2, n+1):
            modinv[i] = self.mod - self.mod//i * modinv[self.mod%i] % self.mod
        return modinv

#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
# dfs のサンプル
def dfs(graph,parent,counter,edge):
    stk = []
    stk.append(edge)
    while len(stk) > 0:
        p = stk.pop()
        for e in graph[p]:
            if parent[p] == e:
                continue
            else:
                parent[e] = p
                counter[e] += counter[p]
                stk.append(e)

#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
if __name__ == "__main__":
	main()

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
mass = [input() for _ in range(H)]
for i in range(H):
    for j in range(W):
        if mass[i][j] == '.':
            count = 0
            if 0 <= i - 1:
                if 0 <= j - 1:
                    if mass[i - 1][j - 1] == '#':
                        count += 1
                if mass[i - 1][j] == '#':
                    count += 1
                if j + 1 < W:
                    if mass[i - 1][j + 1] == '#':
                        count += 1

            if 0 <= j - 1:
                if mass[i][j - 1] == '#':
                    count += 1
            if mass[i][j] == '#':
                count += 1
            if j + 1 < W:
                if mass[i][j + 1] == '#':
                    count += 1

            if i + 1 < H:
                if 0 <= j - 1:
                    if mass[i + 1][j - 1] == '#':
                        count += 1
                if mass[i + 1][j] == '#':
                    count += 1
                if j + 1 < W:
                    if mass[i + 1][j + 1] == '#':
                        count += 1
            print(count, end='')
        else:
            print('#', end='')
    print()

Submission status: Accepted

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

for i in range(h):
  for j in range(w):
    if s[i][j] != '#':
      cnt = 0
      if 0<=i-1:
        if 0<=j-1:
          if s[i-1][j-1] == '#':
            cnt+=1
        if s[i-1][j] == '#':
          cnt+=1
        if j+1<w:
          if s[i-1][j+1] == '#':
            cnt+=1
      if 0<=j-1:
        if s[i][j-1] == '#':
          cnt+=1
      if j+1<w:
        if s[i][j+1] == '#':
          cnt+=1
      if i+1 < h:
        if 0<=j-1:
          if s[i+1][j-1] == '#':
            cnt+=1
        if s[i+1][j] == '#':
          cnt+=1
        if j+1<w:
          if s[i+1][j+1] == '#':
            cnt+=1
      s[i][j] = str(cnt)

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

Submission status: Accepted

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

def find_mines(x, y):
  if field[x][y] == '#':
    return '#'
  else:
    cnt = 0
    for i in range(x - 1, x + 2):
      for j in range(y - 1, y + 2):
        if i < 0 or i > h - 1 or j < 0 or j > w -1 or (i == x and j == y):
          continue
        else:
          if field[i][j] == '#':
            cnt += 1
    return str(cnt)

ans = field[::]
for idx1, i in enumerate(ans):
  for idx2, _j in enumerate(i):
    ans[idx1][idx2] = find_mines(idx1, idx2)

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

Submission status: Accepted

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

ans = [[0]*w for i in range(h)]
for i in range(h):
    for j in range(w):
        if S[i][j] == '#':
            ans[i][j] = '#'
        else:
            cnt = 0
            for di, dj in (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1):
                ni, nj = i+di, j+dj
                if 0 <= ni <= h-1 and 0 <= nj <= w-1:
                    if S[ni][nj] == '#':
                        cnt += 1
            ans[i][j] = str(cnt)
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)]

Ans = [[S[h][w] for w in range(W)] for h in range(H)]

for h in range(H):
    for w in range(W):
        if Ans[h][w] == '.':
            x = 0
            for i in [-1, 0, 1]:
                for j in [-1, 0, 1]:
                    if 0 <= h + i and h + i < H and 0 <= w + j and w + j < W and S[h + i][w + j] == '#':
                        x += 1
            Ans[h][w] = x

for h in range(H):
    for w in range(W):
        print(Ans[h][w], end="")
    print("")

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
B = [[0 for i in range(W)] for j in range(H)]
for i in range(H):
  a = list(input())
  for j in range(W):
    if a[j] == '#':
      B[i][j] = '#'
      if i-1>=0 and j-1>=0 and B[i-1][j-1]!='#':
        B[i-1][j-1] += 1
      if i-1>=0 and B[i-1][j]!='#':
        B[i-1][j] += 1
      if i-1>=0 and j+1<W and B[i-1][j+1]!='#':
        B[i-1][j+1] += 1
      if j-1>=0 and B[i][j-1]!='#':
        B[i][j-1] += 1
      if j+1<W and B[i][j+1]!='#':
        B[i][j+1] += 1
      if i+1<H and j-1>=0 and B[i+1][j-1]!='#':
        B[i+1][j-1] += 1
      if i+1<H and B[i+1][j]!='#':
        B[i+1][j] += 1
      if i+1<H and j+1<W and B[i+1][j+1]!='#':
        B[i+1][j+1] += 1
for i in range(H):
  ans = ''.join([str(n) for n in B[i]])
  print(ans)

Submission status: Accepted

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

A = [[""]*W for _ in range(H)]
for h in range(1,H+1):
    for w in range(1,W+1):
        if S[h][w] == "#":
            A[h-1][w-1] = "#"
        else:
            temp = 0
            for dx in range(-1,2):
                for dy in range(-1,2):
                    if S[h+dy][w+dx] == "#":
                        temp += 1
            A[h-1][w-1] = str(temp)
for e in A:
    print("".join(e))

Submission status: Accepted

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

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


for i in range(H):
    for j in range(W):
        if S[i][j] == "#":
            ans[i][j] = "#"
        else:
            if H == 1:
                li = [i]
            elif 0 < i and i < H-1:
                li = [i-1, i, i+1]
            elif i == 0:
                li = [i, i+1]
            else:
                li = [i-1, i]
            if W == 1:
                lj = [j]
            elif 0 < j and j < W-1:
                lj = [j-1, j, j+1]
            elif j == 0:
                lj = [j, j+1]
            else:
                lj = [j-1, j]
            ans[i][j] = str(sum([S[lii][ljj]=="#" for lii in li for ljj in lj]))

for i in range(H):
    s = "".join(ans[i])
    print(s)

Submission status: Accepted

Solution code:
from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from fractions import gcd
from itertools import combinations # (string,3) 3回
from collections import deque
from collections import defaultdict
import bisect
#
#    d = m - k[i] - k[j]
#    if kk[bisect.bisect_right(kk,d) - 1] == d:
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#

import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7

def readInts():
  return list(map(int,input().split()))
def I():
  return int(input())
h,w = readInts()
dist = [['0'] * w for _ in range(h)]
maze = [input() for _ in range(h)]
dx = [-1,-1,-1,0,0,1,1,1]
dy = [-1,0,1,-1,1,-1,0,1]

def bfs(y,x):
    dist[y][x] = '#'
    for i in range(8):
        nx = x + dx[i]
        ny = y + dy[i]
        if not(0 <= nx < w and 0 <= ny < h):
            continue
        if maze[ny][nx] == '#':
            continue
        dist[ny][nx] = str(int(dist[ny][nx]) + 1)


for y in range(h):
    for x in range(w):
        if maze[y][x] == '#':
            bfs(y,x)
for i in range(h):
    print("".join(dist[i]),sep = '')

Submission status: Accepted

Solution code:
# ABC075/B
h, w = map(int, input().split())
S = [list(input()) for i in range(h)]
for i in range(h):
    for j in range(w):
        cnt = 0
        if S[i][j] == '.':
            for di in (-1, 0, 1):
                for dj in (-1, 0, 1):
                    if 0 <= i + di < h and 0 <= j + \
                            dj < w and S[i + di][j + dj] == '#':
                        cnt += 1
            S[i][j] = str(cnt)
    print(''.join(S[i]))

Submission status: Accepted

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

bom = deque()
for i in range(h):
  for j in range(w):
    if s[i][j] == "#": bom.append([i,j])
    else: s[i][j] = 0

while bom:
  x,y = bom.pop()
  for i,j in [(0,1), (1,0), (-1,0), (0,-1), (1,1), (1,-1), (-1,1), (-1,-1)]:
    new_h, new_w = x+i, y+j
    if new_h < 0 or new_h >= h or new_w < 0 or new_w >= w: continue
    if s[new_h][new_w] == "#": continue
    s[new_h][new_w] += 1
for v in s:
  print("".join(map(str, v)))

Submission status: Accepted

Solution code:
def f(i,j):
    cnt = 0
    if j<W-1 and A[i][j+1]=="#":
        cnt += 1
    if j<W-1 and i>=1 and A[i-1][j+1]=="#":
        cnt += 1
    if i>=1 and A[i-1][j]=="#":
        cnt += 1
    if i>=1 and j>=1 and A[i-1][j-1]=="#":
        cnt += 1
    if j>=1 and A[i][j-1]=="#":
        cnt += 1
    if i<H-1 and j>=1 and A[i+1][j-1]=="#":
        cnt += 1
    if i<H-1 and A[i+1][j]=="#":
        cnt += 1
    if i<H-1 and j<W-1 and A[i+1][j+1]=="#":
        cnt += 1
    A[i][j] = str(cnt)
H,W = map(int,input().split())
A = [list(input().strip()) for _ in range(H)]
for i in range(H):
    for j in range(W):
        if A[i][j]==".":
            f(i,j)
for i in range(H):
    print("".join(A[i]))

Submission status: Accepted

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

for i in range(h):
    for j in range(w):
        if lst[i][j] == '#':
            continue
        cnt = 0
        if i-1>=0:
            if lst[i-1][j] == '#':
                cnt += 1
            if j-1>=0:
                if lst[i-1][j-1] == '#':
                    cnt += 1
            if j+1 < w:
                if lst[i-1][j+1] == '#':
                    cnt += 1
        if j-1 >= 0:
            if lst[i][j-1] == '#':
                cnt += 1
            if i+1 < h:
                if lst[i+1][j-1] == '#':
                    cnt += 1
        if i+1 < h:
            if lst[i+1][j] == '#':
                cnt += 1
            if j+1 < w:
                if lst[i+1][j+1] == '#':
                    cnt += 1
        if j+1 < w:
            if lst[i][j+1] == '#':
                cnt += 1
        lst[i][j] = str(cnt)

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

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)]

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):
        if S[i][j] == "#":
            for k in range(8):
                nx = j + dx[k]
                ny = i + dy[k]
                if nx < 0 or nx >= w:
                    continue
                if ny < 0 or ny >= h:
                    continue
                ans[ny][nx] += 1

for i in range(h):
    for j in range(w):
        if S[i][j] == "#":
            ans[i][j] = "#"

for i in range(h):
    print(*ans[i], sep="")

Submission status: Accepted

Solution code:
def search(i,j):
    res = 0
    for dx,dy in vec:
        x = i+dx
        y = j+dy

        if 0 <= x < H and 0 <= y < W:
            res += int(m[x][y] == "#") 
    return res
    
H,W = map(int,input().split())

m = [input() for _ in range(H)]

vec = [[1,0],[-1,0],[0,1],[0,-1],[1,1],[1,-1],[-1,-1],[-1,1]]

for i in range(H):
    tmp = ""
    for j in range(W):
        if m[i][j] == "#":
            tmp += "#"
        else:
            tmp += str(search(i,j))
    print(tmp)

Submission status: Accepted

Solution code:
import sys
# input = sys.stdin.readline
sys.setrecursionlimit(10 ** 9)
MOD = 10 ** 9 + 7

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

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

for h in range(H):
    for w in range(W):
        if S[h][w] == '#':
            G[h][w] = '#'
            continue
        tmp = 0
        for i in range(-1, 2, 1):
            for j in range(-1, 2, 1):
                if (0 <= h + i < H and 0 <= w + j < W):
                    if S[h + i][w + j] == '#':
                        tmp += 1
        G[h][w] = tmp

for tmp in G:
    print (*tmp, sep = '')

Submission status: Accepted

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()

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

def dfs(x, y):
    cnt = 0
    for i in range(x - 1, x + 2):
        for j in range(y - 1, y + 2):
            if i == x and j == y:
                continue
            if 0 <= i < h and 0 <= j < w:
                if s[i][j] == "#":
                    cnt += 1
    return cnt

for i in range(h):
    for j in range(w):
        if s[i][j] == ".":
            s[i][j] = str(dfs(i, j))
for i in s:
    print("".join(i))

Submission status: Accepted

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

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

for i in range(H):
    for j in range(W):
        if S[i][j]=='.':
            cnt = 0
            
            for dx in range(-1, 2):
                for dy in range(-1, 2):
                    ni = i+dx
                    nj = j+dy
                    
                    if 0<=ni<H and 0<=nj<W and S[ni][nj]=='#':
                        cnt += 1
            
            S[i][j] = str(cnt)
    
for Si in S:
    print(''.join(Si))

Submission status: Accepted

Solution code:
import sys, 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
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

H, W = MAP()
S = ["."*(W+2)]+["."+input()+"." for _ in range(H)]+["."*(W+2)]
dx = [0, -1, -1, -1, 0, 1, 1 ,1]
dy = [1, 1, 0, -1, -1, -1, 0, 1]

ans = [[""]*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] = "#"
			continue
		cnt = 0
		for k in range(8):
			ny = i+dy[k]
			nx = j+dx[k]
			if S[ny][nx] == "#":
				cnt += 1
		ans[i-1][j-1] = str(cnt)


for x in ans:
	print("".join(x), sep="")

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
s = [input() for _ in range(h)]
ans = [[0 for _ in range(w)] for _ in range(h)]
for i in range(h):
    for j in range(w):
        if s[i][j] == '#':
            ans[i][j] = '#'
        else:
            left = max(0, j-1)
            right = min(w-1, j+1)
            top = max(0, i-1)
            bottom = min(h-1, i+1)
            for k in range(top, bottom+1):
                ans[i][j] += s[k][left:right+1].count('#')
for i in range(h):
    for j in range(w):
        print(ans[i][j], end='')
    print()

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
s=[input() for _ in range(h)]
ans=[""]*h
for i in range(h):
    for j in range(w):
        num=0
        if s[i][j]=="#":
            ans[i]+="#"
        else:
            if i!=0 and j!=0 and s[i-1][j-1]=="#":
                num+=1
            if i!=0 and s[i-1][j]=="#":
                num+=1
            if i!=0 and j!=w-1 and s[i-1][j+1]=="#":
                num+=1
            if j!=0 and s[i][j-1]=="#":
                num+=1
            if j!=w-1 and s[i][j+1]=="#":
                num+=1
            if i!=h-1 and j!=0 and s[i+1][j-1]=="#":
                num+=1
            if i!=h-1 and s[i+1][j]=="#":
                num+=1
            if i!=h-1 and j!=w-1 and s[i+1][j+1]=="#":
                num+=1
            ans[i]+=str(num)
for i in range(h):
    print(ans[i])

Submission status: Accepted

Solution code:
import numpy as np

def dot_to_zero(letter):
    if letter == ".":
        return "0"
    else:
        return "#"

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

a = []
for i in range(h):
    s = np.array(list(map(dot_to_zero, input())))
    a.append(s)
a = np.vstack(a)

def add(array):
    for hei in [0,1,2]:
        for wid in [0,1,2]:
            if array[hei][wid] == "#":
                array[hei][wid] = "#"
            else:
                array[hei][wid] = str(int(array[hei][wid]) + 1)
    return array

a = np.pad(a, (1,1), 'edge')


for index_h in range(1, h+1):
    for index_w in range(1, w+1):
        if a[index_h][index_w] == "#":
            a[index_h-1:index_h+2, index_w-1:index_w+2] = add(a[index_h-1:index_h+2, index_w-1:index_w+2])
            
a = a[1:-1, 1:-1]

for array in a:
    print("".join( array.tolist() ))

Submission status: Accepted

Solution code:
import sys

input_methods=['clipboard','file','key']
using_method=0
input_method=input_methods[using_method]

tin=lambda : map(int, input().split())
lin=lambda : list(tin())
mod=1000000007

#+++++

def main():
	#a = int(input())
	h, w = tin()
	#s = input()
	m = []
	for _ in range(h):
		s = input()
		m.append(s)
	ret = [['#']*w for _ in range(h)]
	
	for hi in range(h):
		for wi in range(w):
			p=0
			if m[hi][wi]=='#':
				continue
			for dh in [1, 0, -1]:
				if hi+dh < 0 or hi+dh >= h:
					continue
				for dw in [1, 0, -1]:
					if wi+dw < 0 or wi+dw >= w:
						continue
					if dh == 0 and dw == 0:
						continue
					if m[hi+dh][wi+dw]=='#':
						p+=1
			ret[hi][wi]=p
	for v in ret:
		print(''.join([str(i) for i in v]))
	
	
	
#+++++
isTest=False

def pa(v):
	if isTest:
		print(v)
		
def input_clipboard():
	import clipboard
	input_text=clipboard.get()
	input_l=input_text.splitlines()
	for l in input_l:
		yield l

if __name__ == "__main__":
	if sys.platform =='ios':
		if input_method==input_methods[0]:
			ic=input_clipboard()
			input = lambda : ic.__next__()
		elif input_method==input_methods[1]:
			sys.stdin=open('inputFile.txt')
		else:
			pass
		isTest=True
	else:
		pass
		#input = sys.stdin.readline
			
	ret = main()
	if ret is not None:
		print(ret)

Submission status: Accepted

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

ans = [[0]*W for i in range(H)]
for i in range(H):
  for j in range(W):
    if S[i][j] == '#':
      ans[i][j] = '#'

dxy = [[1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]]
for i in range(H):
  for j in range(W):
    if ans[i][j] == '#':
      continue
    temp = 0
    for dx, dy in dxy:
      ii = i+dx; jj = j + dy
      if 0<=ii<H and 0<=jj<W and S[ii][jj] == '#':
        temp += 1
    ans[i][j] = temp

for a in ans:
  print(*a, sep='')

Submission status: Accepted

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

ab = [input() for i in range(h)]

dp=[[0 for i in range(w+2)] for j in range(h+2)]



for i in range(h):
    sl =  list(ab[i])
    for j in range(w):
        if sl[j]=="#":
            for k in range(3):
                for l in range(3):
                    dp[i+k][j+l] +=1

for i in range(h):
    sl = list(ab[i])
    res = ""
    for j in range(w):
        
        if sl[j]=="#":
            res += "#"
        else:
            res += str(dp[i+1][j+1])
    print(res)

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
M = [[0 if s == '.' else '#' for s in input()] for _ in range(H)]

m = ((1, 0), (-1, 0), (0, 1), (0, -1), (-1, -1), (1, 1), (-1, 1), (1, -1))

for i in range(H):
    for j in range(W):
        if M[i][j] == '#':
            for mi, mj in m:
                ni, nj = i+mi, j+mj
                if 0 <= ni < H and 0 <= nj < W and M[ni][nj] != '#':
                    M[ni][nj] += 1
    
for l in M:
    print(''.join(map(str, l)))

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
s = [[j for j in input()] for i in range(h)]
dij = [(1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1)]
for i in range(h):
    for j in range(w):
        if s[i][j] == '#':
            continue
        cnt = 0
        for di, dj in dij:
            ni, nj = i + di, j + dj
            if 0 <= ni < h and 0 <= nj < w and s[ni][nj] == '#':
                cnt += 1
        s[i][j] = cnt
for i in range(h):
    print(*s[i], sep='')

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
field = [input() for _ in range(H)]
ans = [["."] * W for _ in range(H)]
for i in range(H):
    for j in range(W):
        if field[i][j] == "#":
            ans[i][j] = "#"
            continue
        cnt = 0
        for di, dj in ((1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1), (0, 1), (1, 1),):
            ni = i + di
            nj = j + dj
            if 0 <= ni < H and 0 <= nj < W and field[ni][nj] == "#":
                cnt += 1
        ans[i][j] = str(cnt)
[print("".join(row)) for row in ans]

Submission status: Accepted

Solution code:
h,w = map(int, input().split())
grid = [[0]*(w+2) for _ in range(h+2)]
original = [0]*h
for i in range(h):
  original[i] = input()
for i in range(h):
  for j in range(w):
    if original[i][j]=='#':
      grid[i][j] += 1
      grid[i+1][j] += 1
      grid[i+2][j] += 1
      grid[i][j+1] += 1
      grid[i][j+2] += 1
      grid[i+1][j+1] += 1
      grid[i+1][j+2] += 1
      grid[i+2][j+1] += 1
      grid[i+2][j+2] += 1

for i in range(h):
  output=''
  for j in range(w):
    if original[i][j]=='.':
      output+= str(grid[i+1][j+1])
    else:
      output += '#'
  print(output)

Submission status: Accepted

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

for i in range(1,h+1):
    ans=''
    for j in range(1,w+1):
        if l[i][j] == '#':
            ans += '#'
        else:
            _tmp = l[i-1][j-1:j+2]+l[i][j-1:j+2]+l[i+1][j-1:j+2]
            ans+=str(_tmp.count('#'))
    print(ans)

Submission status: Accepted

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

for i in range(H):
    for j in range(W):
        count = 0
        search = [[i-1, j-1], [i-1, j], [i-1, j+1], [i, j-1], [i, j+1], [i+1, j-1], [i+1, j], [i+1, j+1]]
        if S[i][j] == '#':
            continue
        for k in search:
            if k[0]<0 or k[0]>=H or k[1]<0 or k[1]>=W:
                continue
            if S[k[0]][k[1]] == '#':
                count += 1
        S[i][j] = str(count)

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