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())      
board = []                          

d = [(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1),(1,0)]

for i in range(H):
    board.append(list(input().replace('.','0')))

print("\n")

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

        mine_number = 0

        for k in range(8):

            ii,jj = i + d[k][0], j + d[k][1]

            if ii < 0 or ii>=H: continue    
            if jj < 0 or jj>=W: continue
            if (board[ii][jj] == '#'): mine_number += 1

            board[i][j] = str(mine_number)

for b in board:
    print("".join(b))

Submission status: Accepted

Solution code:
import sys


def check(newLine, index, row, col):
    count = 0

    # 左と右
    if index % col != 0:  # 0列でない
        if newLine[index - 1] == "#":
            count += 1
    if index % col != col - 1:  # 末列でない
        if newLine[index + 1] == "#":
            count += 1
    # 上と下
    if index >= col:  # 首行でない
        if newLine[index - col] == "#":
            count += 1
    if index < col * (row - 1):  # 末行でない
        if newLine[index + col] == "#":
            count += 1

    # 上の左と右 0 <= index + col + 1 < len(newLine) and
    if index >= col and index % col != 0:  # 首行でない かつ　0列でない
        if newLine[index - col - 1] == "#":
            count += 1
    if index >= col and index % col != col - 1:  # 首行でない かつ　末列でない
        if newLine[index - col + 1] == "#":
            count += 1
    # 下の左と右
    if index < col * (row - 1) and index % col != 0:
        if newLine[index + col - 1] == "#":
            count += 1
    if index < col * (row - 1) and index % col != col - 1:
        if newLine[index + col + 1] == "#":
            count += 1

    newLine[index] = str(count)
    return newLine


def main(row, col, lines):
    for index, value in enumerate(lines):
        if value == ".":
            lines = check(lines, index, row, col)
    for i in range(0, len(lines), col):
        print("".join(lines[i:i + col]))


if __name__ == '__main__':
    row, col = map(int, input().split())
    lines = list("".join(list(str(input()) for i in range(row))))
    main(row, col, lines)

Submission status: Accepted

Solution code:
import sys


def check(newLine, index, row, col):
    count = 0

    # 左と右
    if index % col != 0:# 0列でない
        if newLine[index - 1] == "#":
            count += 1
    if index % col != col - 1:# 末列でない
        if newLine[index + 1] == "#":
            count += 1
    # 上と下
    if index >= col: #首行でない
        if newLine[index - col] == "#":
            count += 1
    if index < col * (row - 1):#末行でない
        if newLine[index + col] == "#":
            count += 1

    # 上の左と右 0 <= index + col + 1 < len(newLine) and
    if index >= col and index % col != 0: #首行でない かつ　0列でない
        if newLine[index - col - 1] == "#":
            count += 1
    if index >= col and index % col != col - 1: #首行でない かつ　末列でない
        if newLine[index - col + 1] == "#":
            count += 1
    # 下の左と右
    if index < col * (row - 1) and index % col != 0:
        if newLine[index + col - 1] == "#":
            count += 1
    if index < col * (row - 1) and index % col != col - 1:
        if newLine[index + col + 1] == "#":
            count += 1

    newLine[index] = str(count)
    return newLine


def main(row,col,lines):

    newLine = list("".join(lines))
    for index, value in enumerate(newLine):
        if value == ".":
            newLine = check(newLine, index, row, col)
    for i in range(0, len(newLine), col):
        print("".join(newLine[i:i + col]))


if __name__ == '__main__':
    #lines = ['6 6', '#####.', '#.#.##', '####.#', '.#..#.', '#.##..', '#.#...']
    # lines = ['6 5', '.##.#', '.####', '..##.', '..#..', '.....', '.....']
    #lines = ['3 5', '.....', '.#.#.', '.....']

    row, col = map(int, input().split())
    lines = list(str(input()) for i in range(row))
    #lines = []
    #for l in sys.stdin:
    #    lines.append(l.rstrip('\r\n'))
    main(row,col,lines)

Submission status: Accepted

Solution code:
import numpy as np

h, w = map(int, input().strip().split())
table = [input().strip() for _ in range(h)]

numbers = np.zeros((h, w), dtype=np.int)

for i in range(h):
    for j in range(w):
        # 上
        up    = 1 if i > 0 and table[i - 1][j] == '#' else 0
        # 下
        down  = 1 if i < h - 1 and table[i + 1][j] == '#' else 0
        # 左
        left  = 1 if j > 0 and table[i][j - 1] == '#' else 0
        # 右
        right = 1 if j < w - 1 and table[i][j + 1] == '#' else 0
        # 左上
        left_up = 1 if j > 0 and i > 0 and table[i - 1][j - 1] == '#' else 0
        # 左下
        left_down = 1 if j > 0 and i < h - 1 and table[i + 1][j - 1] == '#' else 0
        # 右下
        right_down = 1 if j < w - 1 and i < h - 1 and table[i + 1][j + 1] == '#' else 0
        # 右上
        right_up = 1 if j < w - 1 and i > 0 and table[i - 1][j + 1] == '#' else 0

        numbers[i][j] = up + down + left + right \
                      + left_up + left_down + right_down + right_up


for i in range(h):
    for j in range(w):
        if table[i][j] == '#':
            print('#', end='')
        else:
            print(numbers[i][j], end='')
    print('')

Submission status: Accepted

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

if H ==1 and W ==1:
    if S[0][0] == ".":
        Answer[0][0] = 0
    for rooms in Answer:
        room=[str(a) for a in rooms]
        room = "".join(room)
        print(room)
    exit()


elif H == 1:
    if S[0][0] == ".":
        if S[0][1] == "#":
            Answer[0][0] = 1
        else:
            Answer[0][0] = 0
    if S[0][W-1] == ".":
        if S[0][W-2] == "#":
            Answer[0][W-1] = 1
        else:
            Answer[0][W-1] = 0
    for i in range(1, W-1):
        count = 0
        if S[0][i] == ".":
            if S[0][i-1] == "#":
                count += 1
            if S[0][i+1] == "#":
                count += 1
            Answer[0][i] = count
    for rooms in Answer:
        room=[str(a) for a in rooms]
        room = "".join(room)
        print(room)
    exit()

elif W == 1:
    if S[0][0] == ".":
        if S[1][0] == "#":
            Answer[0][0] = 1
        else:
            Answer[0][0] = 0
    if S[H-1][0] == ".":
        if S[H-2][0] == "#":
            Answer[H-1][0] = 1
        else:
            Answer[H-1][0] = 0
    for i in range(1, H-1):
        count = 0
        if S[i][0] == ".":
            if S[i-1][0] == "#":
                count += 1
            if S[i+1][0] == "#":
                count += 1
            Answer[i][0] = count
    for rooms in Answer:
        room=[str(a) for a in rooms]
        room = "".join(room)
        print(room)
    exit()

if S[0][0] == ".":
    count = 0
    if S[0][1] == "#":
        count += 1
    if S[1][0] == "#":
        count += 1
    if S[1][1] == "#":
        count += 1
    Answer[0][0] = count

if S[0][W-1] == ".":
    count = 0
    if S[0][W-2] == "#":
        count += 1
    if S[1][W-1] == "#":
        count += 1
    if S[1][W-2] == "#":
        count += 1
    Answer[0][W-1] = count

if S[H-1][0] == ".":
    count = 0
    if S[H-1][1] == "#":
        count += 1
    if S[H-2][0] == "#":
        count += 1
    if S[H-2][1] == "#":
        count += 1
    Answer[H-1][0] = count

if S[H-1][W-1] == ".":
    count = 0
    if S[H-1][W-2] == "#":
        count += 1
    if S[H-2][W-1] == "#":
        count += 1
    if S[H-2][W-2] == "#":
        count += 1
    Answer[H-1][W-1] = count

for i in range(1, W-1):
    count = 0
    if S[0][i] == ".":
        if S[0][i-1] == "#":
            count += 1
        if S[0][i+1] == "#":
            count += 1
        if S[1][i] == "#":
            count += 1
        if S[1][i-1] == "#":
            count += 1
        if S[1][i+1] == "#":
            count += 1
        Answer[0][i] = count

for i in range(1, W-1):
    count = 0
    if S[H-1][i] == ".":
        if S[H-1][i-1] == "#":
            count += 1
        if S[H-1][i+1] == "#":
            count += 1
        if S[H-2][i] == "#":
            count += 1
        if S[H-2][i-1] == "#":
            count += 1
        if S[H-2][i+1] == "#":
            count += 1
        Answer[H-1][i] = count

for i in range(1, H-1):
    count = 0
    if S[i][0] == ".":
        if S[i][1] == "#":
            count += 1
        if S[i-1][0] == "#":
            count += 1
        if S[i-1][1] == "#":
            count += 1
        if S[i+1][0] == "#":
            count += 1
        if S[i+1][1] == "#":
            count += 1
        Answer[i][0] = count

for i in range(1, H-1):
    count = 0
    if S[i][W-1] == ".":
        if S[i][W-2] == "#":
            count += 1
        if S[i-1][W-1] == "#":
            count += 1
        if S[i-1][W-2] == "#":
            count += 1
        if S[i+1][W-1] == "#":
            count += 1
        if S[i+1][W-2] == "#":
            count += 1
        Answer[i][W-1] = count

for i in range(1, H-1):
    for j in range(1, W-1):
        count = 0
        if S[i][j] == ".":
            if S[i-1][j-1] == "#":
                count += 1
            if S[i-1][j] == "#":
                count += 1
            if S[i-1][j+1] == "#":
                count += 1
            if S[i][j-1] == "#":
                count += 1
            if S[i][j+1] == "#":
                count += 1
            if S[i+1][j-1] == "#":
                count += 1
            if S[i+1][j] == "#":
                count += 1
            if S[i+1][j+1] == "#":
                count += 1
            Answer[i][j] = count

for rooms in Answer:
    room=[str(a) for a in rooms]
    room = "".join(room)
    print(room)

Submission status: Accepted

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

area = []
area.append(['.' for i in range(w+2)])

for i in range(h):
    l = list(input())
    tmp = ['.']
    tmp.extend(l)
    tmp.extend(['.'])
    area.append(tmp)
area.append(['.' for i in range(w+2)])


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

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
S=[]
for _ in range(h):
    s=list(map(str,input()))
    S.append(s)
def check(x,y):
    if S[x][y]=='#':
        return 1
    else:
        return 0
for i in range(h):
    for j in range(w):
        if S[i][j]=='.':
            count=0
            for ii in range(i-1,i+2):
                for jj in range(j-1,j+2):
                    if ii>=0 and jj>=0 and ii<=h-1 and jj<=w-1:
                        if ii!=i or jj!=j:
                            count+=check(ii,jj)
            S[i][j]=count


for i in range(h):
    for j in range(w):
        print(S[i][j],end='')
    print()

Submission status: Accepted

Solution code:
H,W = list(map(int,input().split()))
S = [list(input().replace('.','0')) for _ in range(H)]
for i in range(H):
    for j in range(W):
        if S[i][j] == '#': continue
        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] == '#':
                    S[i][j] = str(int(S[i][j])+1)
for s in S:
    print(''.join(s))

Submission status: Accepted

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

temp = ['.'] * (W + 2)
S = [temp]

for _ in range(H):
    S.append(['.'] + list(input()) + ['.'])

S.append(temp)

output = []

for i in range(1, H + 1):
    temp = []
    for j in range(1, W + 1):
        s = str(S[i-1][j-1:j+2].count('#') + S[i+1][j-1:j+2].count('#') + (S[i][j-1] + S[i][j+1]).count('#'))
        temp.append('#' if S[i][j] == '#' else s)
    output.append(temp)
for line in output:
    print(''.join(line))

Submission status: Accepted

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

ans=[]
for row in range(len(L)):
    LINE=[]
    for col in range(len(L[row])):
        if L[row][col]=='.':
            cnt=0
            for shiftX, shiftY in [(i,j) for i in [-1,0,1] for j in [-1,0,1] if i!=0 or j!=0]:
                if 0<=row+shiftY<h and 0<=col+shiftX<w:
                    if L[row+shiftY][col+shiftX]=='#':
                        cnt+=1
            LINE.append(str(cnt))
        else:
            LINE.append('#')
    ans.append(LINE)

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

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
pad = '.' * (w + 2)
sl = []
sl.append(pad)
for i in range(h):
  s = '.' + str(input()) + '.'
  sl.append(s)
sl.append(pad)
for i in range(1, h + 1):
  strlist = list(sl[i])
  for j in range(1, w + 1):
    if sl[i][j] == '.':
      wc = 0
      for p in range(i - 1, i + 2):
        for q in range(j - 1, j + 2):
          if sl[p][q] == '#':
            wc += 1
      strlist[j] = str(wc)
  sl[i] = "".join(strlist)
for i in range(1, len(sl) - 1):
  print(sl[i][1:-1])

Submission status: Accepted

Solution code:
import sys, re
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2
from collections import deque, defaultdict, Counter
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
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, heapify
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 = [input() for _ in range(H)]

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

for i in range(H):
	for j in range(W):
		if S[i][j] == "#":
			print("#", end="")
		else:
			cnt = 0
			for k in range(8):
				ny = i + dy[k]
				nx = j + dx[k]
				if 0 <= ny < H and 0 <= nx < W:
					if S[ny][nx] == "#":
						cnt += 1
			print(cnt, end="")
	print()

Submission status: Accepted

Solution code:
def resolve():
    # 整数 1 つ
    # n = int(input())
    # 整数複数個
    h, w = map(int, input().split())
    # 整数 N 個 (改行区切り)
    S = [list(input()) for i in range(h)]
    # 整数 N 個 (スペース区切り)
    # N = list(map(int, input().split()))
    # 整数 (縦 H 横 W の行列)
    # A = [list(map(int, input().split())) for i in range(H)]

    for i in range(h):
        for j in range(w):
            if S[i][j] == "#":
                continue
            else:
                cnt = 0
                for s in range(i-1, i+2):
                    if s >= 0 and s <= h-1:
                        for t in range(j - 1, j + 2):
                            if t >= 0 and t <= w-1:
                                if S[s][t] == "#" and (s != i or t != j):
                                    cnt += 1
                S[i][j] = str(cnt)

    for a in range (h):
        print("".join(S[a]))


resolve()

Submission status: Accepted

Solution code:
H,W = [int(i) for i in input().split()]
line = [input() for i in range(H)]
ans = [[0]*W for i in range(H)]
dir = [[0,1],[1,0],[0,-1],[-1,0],[1,1],[1,-1],[-1,1],[-1,-1]]
for i in range(H):
    for j in range(W):
        if line[i][j] == "#":
            for a,b in dir:
                x = i+a
                y = j+b
                if 0 <= x < H and 0 <= y < W:
                    if ans[x][y] != "#":
                        ans[x][y] += 1
            ans[i][j] = "#"
print("\n".join("".join(map(str, i)) for i in ans))

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
S = []
for _ in range(H):
    S.append(list(input()))
P=[["#"]*W for _ in range(H)]
a = [[-1,0],[-1,-1],[-1,1],[0,1],[0,-1],[1,1],[1,0],[1,-1]]
n = len(a)
for i in range(H):
    for j in range(W):
        if S[i][j] == '.':
            cnt = 0
            for h in range(n):
                if 0 <= i+a[h][0] < H and 0 <= j+a[h][1] < W:
                    if S[i+a[h][0]][j+a[h][1]] == '#':
                        cnt += 1
            P[i][j] = str(cnt)

for i in range(H):
    print(''.join(P[i]))

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
l=[]
for _ in range(h):
    l.append(list(input()))
P=[["#"]*w for _ in range(h)]
x=[[1,0],[1,-1],[1,1],[0,-1],[0,1],[-1,0],[-1,-1],[-1,1]]
for i in range(h):
    for j in range(w):
        s=0
        if l[i][j]!="#":
            for k in range(8):
                if 0<=i+x[k][0]<h and 0<=j+x[k][1]<w:
                    if l[i+x[k][0]][j+x[k][1]]=="#":
                        s+=1
            P[i][j]=str(s)
for c in range(h):
    print("".join(P[c]))

Submission status: Accepted

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

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
from collections import defaultdict
from collections import deque
from functools import lru_cache


#############
# Constants #
#############

MOD = 10**9+7
INF = float('inf')

#############
# Functions #
#############

######INPUT######
def inputI(): return int(input().strip())
def inputS(): return input().strip()
def inputIL(): return list(map(int,input().split()))
def inputSL(): return list(map(str,input().split()))
def inputILs(n): return list(int(input()) for _ in range(n))
def inputSLs(n): return list(input().strip() for _ in range(n))
def inputILL(n): return [list(map(int, input().split())) for _ in range(n)]
def inputSLL(n): return [list(map(str, input().split())) for _ in range(n)]

######OUTPUT######
def Yes(): print("Yes"); return
def No(): print("No"); return

#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n):
    return kaijo_memo[n]
  if(len(kaijo_memo) == 0):
    kaijo_memo.append(1)
  while(len(kaijo_memo) <= n):
    kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n):
    return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0):
    gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n):
    gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if(n == r):
    return 1
  if(n < r or r < 0):
    return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
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

#####MakeDivisors######
def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n -1
    count += 1
  return count

#####ChangeBase#####
def Base_10_to_n(X, n):
  if X//n:
    return Base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def Base_n_to_10(X, n):
  return sum(int(str(X)[-i])*n**i for i in range(len(str(X))))

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count

#############
# Main Code #
#############
H,W = inputIL()
S = inputSLs(H)

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

ans = []
for i in range(H):
  temp = ""
  for j in range(W):
    if S[i][j] == "#":
      temp += "#"
      continue
    count = 0
    for k in range(8):
      ni,nj = i+dy[k],j+dx[k]
      if 0<=ni<H and 0<=nj<W:
        if S[ni][nj] == "#":
          count+= 1
    temp += str(count)
  ans.append(temp)
  
for i in ans:
  print(*i,sep="")

Submission status: Accepted

Solution code:
def check(i,j):
    c=0
    dx=[-1,0 , 1,-1,1,-1,0,1]
    dy=[-1,-1,-1, 0,0, 1,1,1]
    for k in range(8):
        y=i+dy[k]
        x=j+dx[k]
        if x>=0 and x<w and y>=0 and y<h:
            if S[y][x]=="#":
                c+=1
    return c

h,w=map(int,input().split())
S=[input() for i in range(h)] 
for i in range(h):
    s=""
    for j in range(w):
        if S[i][j]=="#":
            s+="#"
        else:
            count=check(i,j)
            s+=str(count)
    print(s)

Submission status: Accepted

Solution code:
y,x=map(int,input().split())
a=["."+input()+"." for i in range(y)]
a=["."*(x+2)]+a+["."*(x+2)]
ans=[]
anss=""
ansss=0
for j in range(1,y+1):
    for i in range(1,x+1):
        if a[j][i]=="#":
            anss+="#"
        else:
            if a[j+1][i]=="#":
                ansss+=1
            if a[j-1][i]=="#":
                ansss+=1
            if a[j][i+1]=="#":
                ansss+=1
            if a[j][i-1]=="#":
                ansss+=1
            if a[j-1][i-1]=="#":
                ansss+=1
            if a[j+1][i-1]=="#":
                ansss+=1
            if a[j+1][i+1]=="#":
                ansss+=1
            if a[j-1][i+1]=="#":
                ansss+=1
            
            anss+=str(ansss)
            ansss=0
    print(anss)
    anss=""

Submission status: Accepted

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

for i in range(h):
    s=input()
    new_string="0"+s+"0"
    t.append(new_string)

t.append(end)

for i in range(1, h+1):
    for j in range(1, w+1):
        if t[i][j]=="#":
            ans[i][j]="#"


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

for i in range(1, h+1):
    for j in range(1, w+1):
        print(ans[i][j], end='')
    print()

Submission status: Accepted

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

tmp = 10**6

ans = [[0] * w for _ in range(h)]
for i in range(h):
   for j in range(w):
      if s[i][j] == '#':
         ans[i][j] = tmp
         if i-1 >= 0:
            ans[i-1][j] += 1
            if j-1 >= 0:
               ans[i-1][j-1] += 1
         if j-1 >= 0:
            ans[i][j-1] += 1
         if i+1 < h:
            ans[i+1][j] += 1
            if j+1 < w:
               ans[i+1][j+1] += 1
         if j+1 < w:
            ans[i][j+1] += 1
         if i-1 >= 0 and j+1 < w:
            ans[i-1][j+1] += 1
         if i+1 < h and j-1 >= 0:
            ans[i+1][j-1] += 1

for x in ans:
   print(''.join(['#' if y >= tmp else str(y) for y in x]))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
def check(i,j):
    c=0
    try:
        if i!=0 and j!=0:
            if S[i-1][j-1]=="#":
                c+=1
    except:
        pass
    try:
        if i!=0:
            if S[i-1][j]=="#":
                c+=1
    except:
        pass
    try:
        if i!=0:
            if S[i-1][j+1]=="#":
                c+=1
    except:
        pass
    try:
        if j!=0:
            if S[i][j-1]=="#":
                c+=1
    except:
        pass
    try:
        if S[i][j+1]=="#":
            c+=1
    except:
        pass
    try:
        if j!=0:
            if S[i+1][j-1]=="#":
                c+=1
    except:
        pass

    try:
        if S[i+1][j]=="#":
            c+=1
    except:
        pass
                            
    try:
        if S[i+1][j+1]=="#":
            c+=1
    except:
        pass
    return c

h,w=map(int,input().split())
S=[input() for i in range(h)] 
#print(S)
for i in range(h):
    s=""
    for j in range(w):
        #print(i,j)
        if S[i][j]=="#":
            s+="#"
        else:
            count=check(i,j)
            #print(count)
            s+=str(count)
    print(s)

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
pad = '.' * (w + 2)
sl = []
sl.append(pad)
for i in range(h):
  s = '.' + str(input()) + '.'
  sl.append(s)
sl.append(pad)
for i in range(1, h + 1):
  strlist = list(sl[i])
  for j in range(1, w + 1):
    if sl[i][j] == '.':
      wc = 0
      for p in range(i - 1, i + 2):
        for q in range(j - 1, j + 2):
          if sl[p][q] == '#':
            wc += 1
      strlist[j] = str(wc)
  sl[i] = "".join(strlist)
for i in range(1, len(sl) - 1):
  print(sl[i][1:-1])

Submission status: Accepted

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

for _ in range(h):
    l = list(input())
    grid.append(l)

def search(a,b):
    if grid[a][b] == "#":
        return "#"

    mine = 0

    if 0 <= a-1 and 0 <= b-1:
        if grid[a-1][b-1] == "#":
            mine += 1

    if 0 <= a-1:
        try:
            if grid[a-1][b] == "#":
                mine += 1
        except:
            pass

        try:
            if grid[a-1][b+1] == "#":
                mine += 1
        except:
            pass

    if 0 <= b-1:
        if grid[a][b-1] == "#":
                mine += 1

        try:
            if grid[a+1][b-1] == "#":
                mine += 1
        except:
            pass

    try:
        if grid[a][b+1] == "#":
            mine += 1
    except:
        pass


    try:
        if grid[a+1][b] == "#":
            mine += 1
    except:
        pass

    try:
        if grid[a+1][b+1] == "#":
            mine += 1
    except:
        pass

    return mine

ans = []
for i in range(h):
    l = []
    for j in range(w):
        l.append(search(i,j))
    ans.append(l)

for i in range(h):
    print(''.join(map(str, ans[i])))

Submission status: Accepted

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

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

def count_bom(i, j):
    count = 0

    for k in range(8):
        cx = j + dx[k]
        cy = i + dy[k]

        if (cx < 0 or cx >= w):
            continue
        if (cy < 0 or cy >= h):
            continue
        count += check(s[cy][cx])

    return count

def check(symbol):
    if (symbol == "#"):
        return 1
    else:
        return 0

def main():
    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] = count_bom(i, j)
            else:
                ans[i][j] = "#"

    for a in ans:
        for b in a:
            print(b, end="")
        print()

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
ans = [[0 for _ in range(w)] for _ in range(h)]
bom_places = []
for i in range(h):
  s = input()
  for j in range(w):
    add_places = [[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]]
    add_idx = set(range(8))
    remove_idx = []
    if s[j] == "#":
      bom_places.append([i,j])
      if i == 0:
        remove_idx += [0, 1, 2]
      if i == h-1:
        remove_idx += [5, 6, 7]
      if j == 0:
        remove_idx += [0, 3, 5]
      if j == w-1:
        remove_idx += [2, 4, 7]
      
      for idx in list(add_idx - set(remove_idx)):
        m, n = add_places[idx]
        ans[m][n] += 1

for i, j in bom_places:
  ans[i][j] = "#"

for i in range(h):
  tmp = ""
  for each in ans[i]:
    tmp += str(each)
  print(tmp)

Submission status: Accepted

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

def check(y, x):
    dx = [1, 0, -1]
    dy = [1, 0, -1]
    for i in dy:
        for j in dx:
            nx = x + j
            ny = y + i
            if 0<=nx<w and 0<=ny<h:
                if  s[ny][nx] == '#':
                    s[y][x] += 1

for i in range(h):
    for j in range(w):
        if s[i][j] == '.':
            s[i][j] = 0
            check(i, j)

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

Submission status: Accepted

Solution code:

h,w=map(int, input().split( ))
s=[input() for _ in range(h)]
a = [-1,0,1]
b=[-1,0,1]
n=[(i,j) for i in a for j in b]
#print(n)
ans=[["#"]*w for _ in range(h)]

for i in range(h):
    for j in range(w):
        tmp=0
        if s[i][j]=="#":
            continue
        for x,y in n:
            if 0<=i+x<h and 0<=j+y<w:
                if (x or y) and s[i+x][j+y]=="#":
                    tmp+=1
        ans[i][j]=str(tmp)
for i in range(h):
    print(''.join(ans[i]))