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 += ["." + input() + "."]
S += ["." * (W + 2)]

ans = [[-1] * W for _ in range(H)]

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

for i in ans:
    p = ["#" if x == -1 else x for x in i]
    print(*p, sep="")

Submission status: Accepted

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

# M_lis上のi,j成分周囲のマスの＃の数を返す関数
def bom_n(M_lis,i,j):
    cnt = 0
    for x in range(i-1,i+2):
        for y in range(j-1,j+2):
            if x == i and y == j:
                continue
            if x<0 or x > H-1 or y < 0 or y > W-1:
                continue
            if M_lis[x][y] == '#':
                cnt += 1
    return cnt

for h in range(H):
    for w in range(W):
        if map_lis[h][w] == '#':
            print('#',end='')
            continue
        else:
            map_lis[h][w] = str(bom_n(map_lis,h,w))
            print(map_lis[h][w],end='')
    print()

Submission status: Accepted

Solution code:
from itertools import *

H, W = map(int, (input().split()))

S = ["?" * (W + 2)]
for i in range(H):
    S += ["?" + input()+ "?"]
S += ["?" * (W + 2)]

ans = []
for h in range(1, H+1):
    line = ""
    for w in range(1, W+1):
        
        def near_mine(h, w):
            nears = []
            for i, j in product(*[(1, 0, -1)] * 2):
                nears += S[h+i][w+j]

            return nears.count("#")
        
        line += str(near_mine(h, w)) if S[h][w] == "." else S[h][w]

    ans += [line]

for i in ans:
    print(i)

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
S = [list(input()) 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] != '#':
            count = 0
            for k in range(8):
                x = i + dx[k]
                y = j + dy[k]

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

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

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
s=[input() for _ in range(h)]
ans=[]
for i in range(h):
    t=''
    for j in range(w):
        if s[i][j]=='#':
            t+='#'
        else:
            cnt=0
            if i>0:
                if s[i-1][j]=='#':
                    cnt+=1
            if i<h-1:
                if s[i+1][j]=='#':
                    cnt+=1
            if j>0:
                if s[i][j-1]=='#':
                    cnt+=1
            if j<w-1:
                if s[i][j+1]=='#':
                    cnt+=1
            if i>0 and j>0:
                if s[i-1][j-1]=='#':
                    cnt+=1
            if i<h-1 and j>0:
                if s[i+1][j-1]=='#':
                    cnt+=1
            if i>0 and j<w-1:
                if s[i-1][j+1]=='#':
                    cnt+=1
            if i<h-1 and j<w-1:
                if s[i+1][j+1]=='#':
                    cnt+=1
            t+=str(cnt)
    ans.append(t)
for a in ans:
    print(a)

Submission status: Accepted

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

L = [""]*H
for i in range(H):
  for j in range(W):
    if S[i][j] == "#":
        L[i] += "#"
    else:
      c = sum(t[max(0,j-1):min(W,j+2)].count("#") for t in S[max(0,i-1):min(H,i+2)])
      L[i] += str(c)
for i in range(H):
  print(L[i])

Submission status: Accepted

Solution code:
def r(x,y):
  global b
  for n in range(3):
    b[x+n][y]+=1
    b[x+n][y+2]+=1
  b[x][y+1]+=1
  b[x+2][y+1]+=1
h,w=map(int,input().split())
a=[0]*h
for _ in range(h):
  a[_]=input()
b=[[0]*(w+2) for _ in range(h+2)]
for i in range(h):
  for j in range(w):
    if a[i][j]=='#':
      r(i,j)
c=['']*h
for i in range(h):
  for j in range(w):
    if a[i][j]=='.':
      c[i]+=str(b[i+1][j+1])
    else:
      c[i]+="#"
for _ in range(h):
  print(c[_])

Submission status: Accepted

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

for i in range(H):
    for j in range(W):
        if S[i][j] != '#':
            continue
        for dx,dy in [(1,0), (-1,0), (0,1), (0,-1), (-1,-1), (-1,1), (1,1), (1,-1)]:
            x,y = j+dx,i+dy
            if x >= W or x < 0 or y < 0 or y >= H:
                continue
            T[y][x] += 1
for i in range(H):
    for j in range(W):
        print('#' if S[i][j] == '#' else T[i][j], end='')
    print()

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
field=[]
nfield=[[] for i in range(h)]
for i in range(h):
  field.append(input())
def check(a,b):
  num=0
  if field[a][b]=="#":
    return
  for i in range(a-1,a+2):
    for j in range(b-1,b+2):
      try:
        if j !=-1 and i!=-1 and field[i][j]=="#":
          num+=1
      except:
        pass
  return num
for i in range(h):
  for j in range(w):
    if field[i][j]==".":
      nfield[i].append(check(i,j))
    else:
      nfield[i].append("#")
for i in range(h):
  for j in range(w):
    if j != w-1:
      print(nfield[i][j],end="")
    else:
      print(nfield[i][j])

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7

def LI(): return list(map(int,input().split()))
def I(): return int(input())
def LS(): return input().split()
def S(): return input()

def main():
  h,w=LI()

  a=[[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]]

  l=[]
  for i in range(h):
    l.append(list(S()))

  for i in range(h):
    for j in range(w):
      if l[i][j]=='#':
        continue
      c=0
      for x in a:
        p=i+x[0]
        q=j+x[1]
        if 0<=p and p<h and 0<=q and q<w:
          if l[p][q]=='#':
            c+=1
      l[i][j]=str(c)

  for x in l:
    print(''.join(x))

main()

Submission status: Accepted

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

ans = []

for i in range(1, H+1):
    s = ''
    for j, x in enumerate(S[i][1:-1]):
        if x == '.':
            num = 0
            for n in range(3):
                for m in range(3):
                    if S[i+n-1][j+1+m-1] == '#':
                        num += 1
            s += str(num)
        else:
            s += x
    ans.append(s)
print(*ans, sep='\n')

Submission status: Accepted

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

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

for h in range(H):
  for w in range(W):
    if l[h][w] == "#":
      continue
    cnt = 0
    for x in range(-1, 2):
      for y in range(-1, 2):
        if h+x >= 0 and w+y >= 0 and h+x < H and w+y < W:
          if l[h+x][w+y] == "#":
            cnt = cnt + 1
    l[h][w] = str(cnt)

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

Submission status: Accepted

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

ls = [[x for x in input()] for _ in range(h)]

for i in range(h):
    ls[i].append(".")
    ls[i].insert(0,".")
a = ["." for _ in range(w+2)]
ls.append(a)
ls.insert(0,a)

ans = [['#' for _ in range(w)] for _ in range(h)]

for j in range(1,h+1):
    for k in range(1,w+1):
        if ls[j][k] == ".":
            c = [ls[j-1][k-1],ls[j-1][k],ls[j-1][k+1],ls[j][k-1],ls[j][k+1],ls[j+1][k-1],ls[j+1][k],ls[j+1][k+1]]
            ans[j-1][k-1] = str(c.count("#"))

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

Submission status: Accepted

Solution code:
def main():
    H, W = map(int, input().split())
    M = []
    for _ in range(H):
        M.append(input())
    ans = [[''] * W for _ in range(H)]
    for i in range(H):
        for j in range(W):
            if M[i][j] == '#':
                ans[i][j] = '#'
                continue
            c = 0
            for ii, jj in [
                (i + 1, j), (i, j + 1), (i - 1, j), (i, j - 1),
                (i + 1, j - 1), (i - 1, j + 1), (i - 1, j - 1), (i + 1, j + 1)
            ]:
                if 0 <= ii < H and 0 <= jj < W:
                    if M[ii][jj] == '#':
                        c += 1
            ans[i][j] = str(c)
    for a in ans:
        print(''.join(a))


main()

Submission status: Accepted

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

x = [-1, 0, 1]
y = [-1, 0, 1]
around = [(i, j) for i in y for j in x if i != 0 or j != 0]

for i in range(h):
    for j in range(w):
        if grid[i][j] == '#':
            continue
        cnt = 0
        for x, y in around:
            if 0 <= i + y <= h - 1 and 0 <= j + x <= w - 1 and grid[i + y][x + j] == '#':
                cnt += 1
        grid[i][j] = str(cnt)

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

Submission status: Accepted

Solution code:
temp=list(map(lambda x:int(x),input().split()))
H,W=temp[0],temp[1]
grid=[]
for _ in range(H):
    row=list(input())
    row.append("?")
    row.insert(0,"?")
    grid.append(row)

pad=["?" for _ in range(W+2)]
grid.append(pad)
grid.insert(0,pad)

dx=[1,0,-1,0,1,1,-1,-1]
dy=[0,1,0,-1,1,-1,1,-1]
for now_y in range(1,H+1):
    line=""
    for now_x in range(1,W+1):
        bom_cnt=0
        if grid[now_y][now_x]=="#":
            line+="#"
            continue
        for i in range(8):
            # print(now_x+dx[i],now_y+dy[i])
            if grid[now_y+dy[i]][now_x+dx[i]]=="#":bom_cnt+=1
        line+=str(bom_cnt)
    print(line)
        # answer_grid[now_y][now_x]=bom_cnt

Submission status: Accepted

Solution code:
import bisect
import os
from collections import Counter, deque
from fractions import gcd
from functools import lru_cache
from functools import reduce
import functools
import heapq
import itertools
import math
import numpy as np
import re
import sys
import string

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")

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

counts = np.zeros((H + 2, W + 2), dtype=int)
for h in range(H):
    for w in range(W):
        if S[h][w] == '#':
            counts[h][w] += 1
            counts[h + 1][w] += 1
            counts[h + 2][w] += 1
            counts[h][w + 1] += 1
            counts[h + 2][w + 1] += 1
            counts[h][w + 2] += 1
            counts[h + 1][w + 2] += 1
            counts[h + 2][w + 2] += 1
c = counts[1:-1, 1:-1].astype(str)
c[S == '#'] = '#'
print('\n'.join(map(lambda r: ''.join(r), c)))

Submission status: Accepted

Solution code:
h,w = map(int,input().split())
lis = [list(input()) for _ in range(h)]
dx = [1,0,-1,0,1,1,-1,-1]
dy = [0,1,0,-1,1,-1,1,-1]

for i in range(h):
  for j in range(w):
    if lis[i][j] == "#":
      continue
    else:
      lis[i][j] = 0
    for d in range(8):
      if i + dx[d] < 0 or i + dx[d] >= h:
        continue
      elif j + dy[d] < 0 or j + dy[d] >= w:
        continue
      if lis[i+dx[d]][j+dy[d]] == "#":
        lis[i][j] += 1
for i in range(h):
  lis[i] = list(map(str,lis[i]))
  print("".join(lis[i]))

Submission status: Accepted

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

import itertools
for i in range(H):
  for j in range(W):
    if S[i][j] != '#':
      continue
    for dx,dy in itertools.product([-1,0,1],repeat=2):
      x = i+dx
      y = j+dy
      if x < 0 or x >= H:
        continue
      if y < 0 or y >= W:
        continue
      if S[x][y] == '#':
        continue
      answer[x][y] += 1

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

Submission status: Accepted

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

Submission status: Accepted

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

ans=lst

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

for y in range(h):
    for x in range(w):
        if lst[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 lst[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:
from collections import defaultdict

def main():
    high, width = map(int, input().split())
    data = [list(input()) for i in range(high)]


    move = [[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]]

    for i in range(high):
        for j in range(width):
            if data[i][j] == '#':
                continue
            bakudan = 0
            for x, y in move:
                if 0 <= x + i < high and 0 <= y + j < width:
                    if data[x + i][y + j] == '#':
                        bakudan += 1

            data[i][j] = str(bakudan)

    for i in range(high):
        print(''.join(data[i]))





if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7

def LI(): return list(map(int,input().split()))
def I(): return int(input())
def LS(): return input().split()
def S(): return input()

def main():
  h,w=LI()

  a=[[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]]

  l=[]
  for i in range(h):
    l.append(list(S()))

  for i in range(h):
    for j in range(w):
      if l[i][j]!='#':
        c=0
        for x in a:
          if i+x[0]>=0 and i+x[0]<h and j+x[1]>=0 and j+x[1]<w:
            if l[i+x[0]][j+x[1]]=='#':
              c+=1

          l[i][j]=str(c)

  for x in l:
    print(''.join(x))

main()

Submission status: Accepted

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

def count(x, y):
    c = 0
    if x-1 >= 0 and s[x-1][y] =="#":
        c += 1
    if x+1 <= H-1 and s[x+1][y] =="#":
        c += 1
    if y-1 >= 0 and s[x][y-1] =="#":
        c += 1
    if y+1 <= W-1 and s[x][y+1] =="#":
        c += 1
    if x-1 >= 0 and y-1>=0 and s[x-1][y-1] =="#":
        c += 1
    if x-1 >= 0 and y+1 <= W-1 and s[x-1][y+1] =="#":
        c += 1
    if x+1 <= H-1 and y-1 >=0 and s[x+1][y-1] =="#":
        c += 1
    if x+1 <= H-1 and y+1 <= W-1 and s[x+1][y+1] =="#":
        c += 1
    return c

ans = [[None] * W for i in range(H)]
for i in range(H):
    for j in range(W):
        ans[i][j] = count(i, j)

for i,line in enumerate(ans):
    for j,num in enumerate(line):
        if s[i][j] == "#":
            print("#", end="")
        else:
            print(num, end="")
    print()

Submission status: Accepted

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

def count(x, y):
    c = 0
    if x-1 >= 0 and s[x-1][y] =="#":
        c += 1
    if x+1 <= H-1 and s[x+1][y] =="#":
        c += 1
    if y-1 >= 0 and s[x][y-1] =="#":
        c += 1
    if y+1 <= W-1 and s[x][y+1] =="#":
        c += 1
    if x-1 >= 0 and y-1>=0 and s[x-1][y-1] =="#":
        c += 1
    if x-1 >= 0 and y+1 <= W-1 and s[x-1][y+1] =="#":
        c += 1
    if x+1 <= H-1 and y-1 >=0 and s[x+1][y-1] =="#":
        c += 1
    if x+1 <= H-1 and y+1 <= W-1 and s[x+1][y+1] =="#":
        c += 1
    return c

ans = [["#"] * W for i in range(H)]
for i in range(H):
    for j in range(W):
        ans[i][j] = count(i, j)

for i,line in enumerate(ans):
    for j,num in enumerate(line):
        if s[i][j] == "#":
            print("#", end="")
        else:
            print(num, end="")
    print()

Submission status: Accepted

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

li = [".." + "." * w]
for i in range(h):
  li.append("." + input() + ".")
li.append(".." + "." * w)

for i in range(1, h+1):
  ans = ""
  for j in range(1, w+1):
    if li[i][j] =="#":
      ans+="#"
    else:
      count = 0
      for a in [-1, 0, 1]:
        for b in [-1, 0, 1]:
          if li[i+a][j+b] == "#":
            count += 1
      ans += str(count)
  print(ans)

Submission status: Accepted

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

for h in range(1,H+1):
  for w in range(1,W+1):
    if S[h][w] == '.':
      num = 0
      for hx,wx in [(0,-1), (0,1), (-1,0), (1,0),(1,-1), (1,1), (-1,1), (-1,-1)]:
        if S[h+hx][w+wx] == '#':
          num += 1
        S[h][w] = str(num)

for h in range(1,H+1):
  print(''.join(S[h][1:-1]))

Submission status: Accepted

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


def num_bombs(h, w):
    if S[h][w] == '#':
        return '#'

    ps = [
        (w - 1, h + 1), (w, h + 1), (w + 1, h + 1),
        (w - 1, h), (w + 1, h),
        (w - 1, h - 1), (w, h - 1), (w + 1, h - 1)
    ]
    ps = [p for p in ps if p[0] in range(W) and p[1] in range(H)]
    return str([S[p[1]][p[0]] for p in ps].count('#'))

result = [[0] * W for _ in range(H)]
for w in range(W):
    for h in range(H):
        result[h][w] = num_bombs(h, w)

print('\n'.join([''.join(r) for r in result]))

Submission status: Accepted

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


def check_around(x, y):
    cnt = 0
    if 0 < x and 0 < y and S_array[y - 1][x - 1] == '#':
        cnt += 1
    if 0 < y and S_array[y - 1][x] == '#':
        cnt += 1
    if x < W - 1 and 0 < y and S_array[y - 1][x + 1] == '#':
        cnt += 1
    if 0 < x and S_array[y][x - 1] == '#':
        cnt += 1
    if x < W - 1 and S_array[y][x + 1] == '#':
        cnt += 1
    if 0 < x and y < H - 1 and S_array[y + 1][x - 1] == '#':
        cnt += 1
    if y < H - 1 and S_array[y + 1][x] == '#':
        cnt += 1
    if x < W - 1 and y < H - 1 and S_array[y + 1][x + 1] == '#':
        cnt += 1
    return cnt


for y in range(H):
    line_str = ''
    for x in range(W):
        cur = S_array[y][x]
        if cur == '.':
            line_str += str(check_around(x, y))
        else:
            line_str += cur
    print(line_str)

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
 
Ss = [[-1 if c == "#" else 0 for c in input()] for _ in range(H)]
 
def plus(i, j):
  if 0 <= i < H and 0 <= j < W:
    if Ss[i][j] >= 0:
      Ss[i][j] += 1
 
for i in range(H):
  for j in range(W):
    if Ss[i][j] != -1:
      continue
    for x, y in ((x,y) for x in range(-1, 2) for y in range(-1, 2)):
      if x != 0 or y != 0:
        plus(i+x, j+y)
 
for i in range(H):
  for j in range(W):
    print("#" if Ss[i][j] == -1 else Ss[i][j], end="")
  print()

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
s=[input() for _ in range(h)]
for i in range(h):
    ans=""
    for j in range(w):
        if(s[i][j] =="#"):
            ans+="#"
        else:
            c=0
            for ss in s[max(0,i-1):min(h,i+2)]:
                c+=ss[max(0,j-1):min(w,j+2)].count("#")
            ans+= str(c)
    print(ans)

Submission status: Accepted

Solution code:
def check_nmine(h,w,matrix):
    count=0
    #h+1 -1 （いっぱい書く）
    if h-1 >= 0 and w-1 >= 0:
        if(matrix[h-1][w-1] == '#'):
            count += 1
    if h-1 >= 0 and w >= 0:
        if(matrix[h-1][w] == '#'):
            count += 1
    if h-1 >= 0 and w+1 < W:
        if(matrix[h-1][w+1] == '#'):
            count += 1
            
    if h >= 0 and w-1 >= 0:
        if(matrix[h][w-1] == '#'):
            count += 1
    if h >= 0 and w+1 < W:
        if(matrix[h][w+1] == '#'):
            count += 1
            
    if h+1 < H and w-1 >= 0:
        if(matrix[h+1][w-1] == '#'):
            count += 1
    if h+1 < H and w >= 0:
        if(matrix[h+1][w] == '#'):
            count += 1
    if h+1 < H and w+1 < W:
        if(matrix[h+1][w+1] == '#'):
            count += 1
            
    return count


H,W = map(int,input().split())



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

for h in range(H):
    for w in range(W):
        if matrix[h][w] != '#':
            matrix[h][w] = str(check_nmine(h,w,matrix))
            
for i in matrix:
    print("".join(i))

Submission status: Accepted

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

for i in range(1, H+1):
    res = ""
    for j in range(1, W+1):
        if s[i][j] == "#":
            res += "#"
            continue
        count = 0
        for k in [-1, 0, 1]:
            for l in [-1, 0, 1]:
                if s[i+k][j+l] == "#":
                    count += 1
        res += str(count)
    print(res)

Submission status: Accepted

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

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

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

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
S=[]
for i in range(H):
    s=input()
    S.append(s)
T=[[0]*W for i in range(H)]
for i in range(H):
    for j in range(W):
        t=False
        for k in [0,-1,1]:
            if t:
                break
            for l in [0,-1,1]:
                if k==0 and l==0 and S[i][j]=="#":
                    T[i][j]="#"
                    t=True
                    break
                if i+k<0 or i+k>=H or j+l<0 or j+l>=W :
                    continue
                if S[i+k][j+l]=="#":
                    T[i][j]+=1
for i in range(H):
    for j in range(W):
        print(T[i][j],end="")
    print()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys


def solve(H: int, W: int, S: "List[str]"):
    ret = []
    for x, R in enumerate(S):
        r = ''
        for y, c in enumerate(R):
            if c == '.':
                tmp = 0
                for i in range(-1, 2):
                    for j in range(-1, 2):
                        if 0 <= x + i < H and 0 <= y + j < W and S[x + i][y + j] == '#':
                            tmp += 1
                r += str(tmp)
            else:
                r += c
        ret.append(r)

    for r in ret:
        print(r)
    return


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:
import copy


def inputs(num_of_input):
    ins = [input() for i in range(num_of_input)]
    return ins


def solve(inputs):
    field = []
    for row in inputs:
        line = []
        for c in row:
            line.append(c)
        field.append(line)

    replaced_field = []
    for i, row in enumerate(field):
        replaced_line = []
        for j, value in enumerate(row):
            if value == "#":
                replaced_line.append(value)
            else:
                count = 0
                if (i - 1) >= 0:
                    if (j - 1) >= 0:
                        count = (count + 1) if field[i - 1][j - 1] == "#" else count
                    if (j + 1) < len(row):
                        count = (count + 1) if field[i - 1][j + 1] == "#" else count
                    count = (count + 1) if field[i - 1][j] == "#" else count
                if (j - 1) >= 0:
                    count = (count + 1) if field[i][j - 1] == "#" else count
                if (j + 1) < len(row):
                    count = (count + 1) if field[i][j + 1] == "#" else count
                if (i + 1) < len(field):
                    if (j - 1) >= 0:
                        count = (count + 1) if field[i + 1][j - 1] == "#" else count
                    if (j + 1) < len(row):
                        count = (count + 1) if field[i + 1][j + 1] == "#" else count
                    count = (count + 1) if field[i + 1][j] == "#" else count
                replaced_line.append(str(count))

        replaced_field.append(replaced_line)

    result = ""
    for row in replaced_field:
        result += "".join(row) + "\n"
    return result.strip("\n")


if __name__ == "__main__":
    n = list(map(lambda x: int(x), input().split()))
    ret = solve(inputs(n[0]))
    print(ret)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

H, W = map(int, input().split())
# 2次元配列を作る
grid = []
for _n in range(H):
    grid.append(list(input()))


def is_bomb(h, w):
    """指定されたマスが爆弾か調べる"""
    try:
        # マイナス位置は全部0扱い
        if h < 0 or w < 0:
            return 0
        if grid[h][w] == "#":
            return 1
        else:
            return 0
    except IndexError:
        return 0


def search_bomb(h, w):
    """指定されたマスの周囲8マスが爆弾か調べて爆弾の数を返す"""
    if grid[h][w] == "#":
        return "#"
    bomb_count = sum(
        [
            is_bomb(h - 1, w - 1),
            is_bomb(h - 1, w),
            is_bomb(h - 1, w + 1),
            is_bomb(h, w - 1),
            is_bomb(h, w + 1),
            is_bomb(h + 1, w - 1),
            is_bomb(h + 1, w),
            is_bomb(h + 1, w + 1),
        ]
    )
    return str(bomb_count)


# 置換後の2次元配列作成
for h in range(H):
    for w in range(W):
        print(search_bomb(h, w), end="")
    # 行が終わったら改行
    print()

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

H, W = map(int, input().split())
# 2次元配列を作る
grid = []
for _n in range(H):
    grid.append(list(input()))


def is_bomb(h, w):
    """指定されたマスが爆弾か調べる"""
    try:
        # マイナス位置は全部0扱い
        if h < 0 or w < 0:
            return 0
        if grid[h][w] == "#":
            return 1
        else:
            return 0
    except IndexError:
        return 0


def search_bomb(h, w):
    """指定されたマスの周囲8マスが爆弾か調べて爆弾の数を返す"""
    if grid[h][w] == "#":
        return "#"
    bomb_count = sum(
        [
            is_bomb(h - 1, w - 1),
            is_bomb(h - 1, w),
            is_bomb(h - 1, w + 1),
            is_bomb(h, w - 1),
            is_bomb(h, w + 1),
            is_bomb(h + 1, w - 1),
            is_bomb(h + 1, w),
            is_bomb(h + 1, w + 1),
        ]
    )
    from logging import getLogger, DEBUG, basicConfig

    logger = getLogger(__name__)
    logger.setLevel(DEBUG)
    basicConfig()
    logger.info(bomb_count)
    return str(bomb_count)


# 置換後の2次元配列作成
for h in range(H):
    for w in range(W):
        print(search_bomb(h, w), end="")
    # 行が終わったら改行
    print()

Submission status: Accepted

Solution code:
viewlist = [-1, 0, 1]
H, W = map(int, input().split())
gametable = []
for i in range(0, H):
	lst = []
	s = input()
	for j in range(0, W):
		lst.append(s[j])
	gametable.append(lst)
for i in range(0, H):
	for j in range(0, W):
		if gametable[i][j] == '.':
			cnt = 0
			for p in range(0, 3):
				lookh = i+viewlist[p]
				if 0 <= lookh and lookh < H:
					for q in range(0, 3):
						lookw = j+viewlist[q]
						if 0 <= lookw and lookw < W:
							if p != 1 or q != 1:
								if gametable[lookh][lookw] == '#':
									cnt += 1
			gametable[i][j] = str(cnt)
for i in range(0, H):
	ans = ''
	for j in range(0, W):
		ans = ans + gametable[i][j]
	print(ans)