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

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

for i in range(H):
    for j in range(W):
    # 地雷数のカウンタ
        c=0

    # '#'の場合はなにもしない
        if l[i][j]=='#':
            pass

    # '#'以外の場合
        else:
      # 左上
            if 0<i and 0<j and l[i-1][j-1]=='#':
                c+=1
      # 上
            if 0<i and l[i-1][j]=='#':
                c+=1
      # 右上
            if 0<i and j<W-1 and l[i-1][j+1]=='#':
                c+=1
      # 左
            if 0<j and l[i][j-1]=='#':
                c+=1
      # 右
            if j<W-1 and l[i][j+1]=='#':
                c+=1
      # 左下
            if i<H-1 and 0<j and l[i+1][j-1]=='#':
                c+=1
      # 下
            if i<H-1 and l[i+1][j]=='#':
                c+=1
      # 右下
            if i<H-1 and j<W-1 and l[i+1][j+1]=='#':
                c+=1

      # 地雷隣接数を記載
            l[i][j]=str(c)

# 出力
for i in range(H):
    print(''.join(l[i]))

Submission status: Accepted

Solution code:
def get_neighbors(x, y):
    neighbors = []
    for i in [-1, 0, 1]:
        for j in [-1, 0, 1]:
            if i == 0 and j == 0:
                continue
            search_y = y + i
            search_x = x + j
            if search_x >= 0 and search_y >= 0 and search_x < W and search_y < H:
                neighbors.append(S[search_y][search_x])
    return neighbors
                
H, W = map(int, input().split())
S = [input() for _ in range(H)]
for y in range(H):
    for x in range(W):
        if S[y][x] == '#':
            print('#', end='')
        else:
            neighbors = get_neighbors(x, y)
            n_mines = neighbors.count('#')
            print(n_mines, end='')
    print()

Submission status: Accepted

Solution code:
H,W=map(int, input().split())
src=[input() for _ in range(H)]
ans=[]
for row in src:
    ans.append(list(row))
dxy = [(-1,-1),(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1)]
for y in range(H):
    for x in range(W):
        if src[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: pass
            elif src[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:
import itertools

H, W = map(int, input().split())
S = [list(input()) for _ in range(H)]
ans = [[0 if c=='.' else '#' for c in s] for s in S]

for i in range(H):
    for j in range(W):
        if S[i][j] == '.': continue
        for di, dj in itertools.product([-1,0,1], repeat=2):
            if not 0 <= i+di < H: continue
            if not 0 <= j+dj < W: continue
            if S[i+di][j+dj] == '#': continue
            ans[i+di][j+dj] += 1

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

Submission status: Accepted

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

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

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

for i in range(1,h+1):
    for j in range(1,w+1):
        cnt = 0
        if Map[i][j]=='#':
            Cnt[i-1][j-1] = '#'
            continue
        for ij in range(i-1,i+2):
            for ji in range(j-1,j+2):
                if ij == i and ji==j:
                    continue
                if Map[ij][ji]=='#':
                    cnt+=1
        Cnt[i-1][j-1] =cnt
for i in range(len(Cnt)):
    ans = map(str,Cnt[i])
    print(''.join(ans))

Submission status: Accepted

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

H, W = map(int, input().split())
field = []

for i in range(H):
    field.append(list(input()))

for y in range(H):
    for x in range(W):

        if field[y][x] == '#':
            continue

        cnt = 0

        for k in range(8):
            ny = y + dy[k]
            nx = x + dx[k]

            if ny<0 or H<=ny or nx<0 or W<=nx:
                continue

            if field[ny][nx] == '#':
                cnt += 1

        field[y][x] = str(cnt)

for y in range(H):
    print("".join(field[y]))

Submission status: Accepted

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

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

for h in range(H):
    l = ""
    for w in range(W):
        if S[h][w] == '#':
            l += '#'
            continue
        num = 0
        for d in range(8):
            nx = h + dx[d]
            ny = w + dy[d]
            if nx < 0 or ny < 0 or nx >= H or ny >= W: continue
            if S[nx][ny] == '#' : num+=1
        l+=str(num)
    S[h] = l


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

Submission status: Accepted

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

for h in range(H):
    for w in range(W):
        no = 0
        if S[h][w] == '.':
            if h != 0 and w != 0:
                if S[h-1][w-1] == '#':
                    no+=1
            if h != 0:
                if S[h-1][w] == '#':
                    no+=1
            if h != 0 and w != W-1:
                if S[h-1][w+1] == '#':
                    no+=1
            if h != H-1 and w != 0:
                if S[h+1][w-1] == '#':
                    no+=1
            if h != H-1:
                if S[h+1][w] == '#':
                    no+=1
            if w != 0:
                if S[h][w-1] == '#':
                    no+=1
            if w != W-1:
                if S[h][w+1] == '#':
                    no+=1
            if h != H-1 and w != W-1:
                if S[h+1][w+1] == '#':
                    no+=1
            S[h][w] = str(no)

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

Submission status: Accepted

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

field=[list(input()) for _ in range(H)]
directions = [[-1, -1], [-1, 0], [-1, 1],
              [0, -1], [0, 1], [1, 0], [1, -1], [1, 1]]
for i in range(H):
    for j in range(W):
        if field[i][j] == '.':
            bombCnt = 0
            for k in directions:
                if (i + k[0] >= 0 and i + k[0] < H) and (j + k[1] >= 0 and j + k[1] < W):
                    if field[i + k[0]][j + k[1]] == '#':
                        bombCnt += 1
            field[i][j] = str(bombCnt)
for i in range(H):
    print("".join(field[i]))

Submission status: Accepted

Solution code:
def valid(i,j):
  return i>=0 and i<h and j>=0 and j<w

def get_adj(i,j):
  points = []
  for k in range(8):
    if valid(x[k]+i,y[k]+j):
      points.append((x[k]+i,y[k]+j))
  return points
h,w = map(int,input().split())
mat = []
for _ in range(h):
  mat.append(list(input()))
x = [0,0,1,1,-1,-1,1,-1]
y = [1,-1,1,-1,1,-1,0,0]
for i in range(h):
  for j in range(w):
    if mat[i][j]=='#':
      continue
    bombs = 0
    for p in get_adj(i,j):
      if mat[p[0]][p[1]]=='#':
        bombs+=1
    mat[i][j] = bombs
for i in range(h):
  for j in range(w):
    print(mat[i][j],end='')
  print()

Submission status: Accepted

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

field = [list(input()) for _ in range(H)]
directions = [[-1, -1], [-1, 0], [-1, 1],
              [0, -1], [0, 1], [1, 0], [1, -1], [1, 1]]
for i in range(H):
    for j in range(W):
        if field[i][j] == '.':
            bombCnt = 0
            for k in directions:
                if (i + k[0] >= 0 and i + k[0] < H) and (j + k[1] >= 0 and j + k[1] < W):
                    if field[i + k[0]][j + k[1]] == '#':
                        bombCnt += 1
            field[i][j] = str(bombCnt)
for i in range(H):
    print("".join(field[i]))

Submission status: Accepted

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


for k,v in enumerate(S):
  for kk,vv in enumerate(list(v)):
    checkTarget = []
    if vv == "#":
      print("#", end="" )
    else:
      if H==1 and W==1:
        print("0" , end="")
        break
      if k == 0 and kk == 0:
        checkTarget = [                         
                                                   S[k][kk+1],
                                     S[k+1][kk], S[k+1][kk+1]]

      elif k == 0 and kk > 0 and kk < len(v)-1 and H==1:
        checkTarget = [ 
                        S[k][kk-1],             S[k][kk+1],
                        ]

      elif k == 0 and kk > 0 and kk < len(v)-1:
        checkTarget = [ 
                        S[k][kk-1],             S[k][kk+1],
                        S[k+1][kk-1], S[k+1][kk], S[k+1][kk+1]]
      elif k == 0 and kk == len(v)-1 and H==1:
        checkTarget = [ 
                        S[k][kk-1],             
                        ]

      elif k == 0 and kk == len(v)-1:
        checkTarget = [ 
                        S[k][kk-1],             
                        S[k+1][kk-1], S[k+1][kk]]
      elif k > 0 and k < len(S) -1 and kk==0 and W==1:
        checkTarget = [       S[k-1][kk],
                                         
                              S[k+1][kk]]

      elif k > 0 and k < len(S) -1 and kk==0:
        checkTarget = [       S[k-1][kk], S[k-1][kk+1],
                                         S[k][kk+1],
                              S[k+1][kk], S[k+1][kk+1]]

      elif k > 0 and k < len(S) -1 and kk==len(v)-1:
        checkTarget = [ S[k-1][kk-1],  S[k-1][kk],
                        S[k][kk-1],             
                        S[k+1][kk-1], S[k+1][kk]]

      elif k == len(S) -1 and kk == 0 and W==1:
        checkTarget = [   S[k-1][kk]
                                     ]
      elif k == len(S) -1 and kk == 0:
        checkTarget = [   S[k-1][kk], S[k-1][kk+1],
                                        S[k][kk+1]
                                                  ]
      elif k == len(S) -1 and kk> 0 and  kk < len(v)-1:
        checkTarget = [ S[k-1][kk-1],  S[k-1][kk], S[k-1][kk+1],
                        S[k][kk-1],                S[k][kk+1]
                                                                ]

      elif k == len(S) -1 and kk == len(v)-1:
        checkTarget = [ S[k-1][kk-1],  S[k-1][kk], 
                        S[k][kk-1]            
                                                               ]

      else:
        checkTarget = [ S[k-1][kk-1],  S[k-1][kk], S[k-1][kk+1],
                        S[k][kk-1],             S[k][kk+1],
                        S[k+1][kk-1], S[k+1][kk], S[k+1][kk+1]]

      print(len( [ i for i in checkTarget if i == "#"]  ), end="")
  print("", end="\n" if k != len(S)-1 else "" )

Submission status: Accepted

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

S = [list(input()) for i in range(h)]
for i in range(h):
  S[i] = ["a"] + S[i] + ["a"]
  
S.insert(0,["a"] * (w+2))
S.append(["a"]*(w+2))

for i in range(1,h+1):
  for j in range(1,w+1):
    if S[i][j] == ".":
      p = 0
      for k in [-1,0,1]:
        for l in [-1,0,1]:
          if S[i-k][j-l] == "#":
            p += 1
      S[i][j] = str(p)

for i in range(1,h+1):
  S[i].pop(0)
  S[i].pop()

ans = []
for i in range(1,h+1):
  ans.append("".join(S[i]))
 
for i in range(len(ans)):
  print(ans[i])

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
S = [[] for _ in range(H)]
for i in range(H):
    S[i] = list(input())
dx = [1, 0, -1, 0, 1, -1, -1, 1]
dy = [0, 1, 0, -1, 1, 1, -1, -1]
for i in range(H):
    for j in range(W):
        if S[i][j] == '.':
            num = 0
            for d in range(8):
                ni = i + dx[d]
                nj = j + dy[d]
                if ni < 0 or H <=ni:
                    continue
                if nj < 0 or W <=nj:
                    continue
                if S[ni][nj] == '#':
                    num += 1
            S[i][j] = num
for i in range(H):
    a = map(str, S[i])
    print("".join(a))

Submission status: Accepted

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


for i in range(h):
  bombs = []
  for j in range(w):
    if a[i][j]=='.':
      cnt = 0
      for s in range(max(i-1, 0), min(i+2,h)):
        for t in range(max(j-1, 0), min(j+2,w)):
          if a[s][t]=='#':
            cnt += 1
      bombs.append(str(cnt))
    else:
      bombs.append('#')
    
  a[i] = ''.join(bombs)
    
for i in range(h):
  print(a[i])

Submission status: Accepted

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

S = [list(input()) for i in range(H)]
ans = [["#"] * W for i in range(H)]

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

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

        num = 0
        for d in range(8):
            ni = i + dy[d]
            nj = j + dx[d]

            if ni < 0 or H <= ni:
                continue

            if nj < 0 or W <= nj:
                continue

            if S[ni][nj] == "#":
                num += 1

        ans[i][j] = str(num)

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

Submission status: Accepted

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

for i in range(H):
  for j in range(W):
    sum=0
    if i!=0:
      sum+=S[i-1][max(0,j-1):min(W,j+2)].count('#')
    sum+=S[i][max(0,j-1):min(W,j+2)].count('#')
    if i!=H-1:
      sum+=S[i+1][max(0,j-1):min(W,j+2)].count('#') 
    if S[i][j]=='.':
      R[i]+=str(sum)
    else:      
      R[i]+='#'
    
print(*R,sep='\n')

Submission status: Accepted

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

for i in range(H):
  for j in range(W):
    sum=0
    if i!=0:
      #print(i,j,'u',S[i-1][max(0,j-1):min(W,j+2)])
      sum+=S[i-1][max(0,j-1):min(W,j+2)].count('#')
    #print(i,j,'m',S[i][max(0,j-1):min(W,j+2)])
    sum+=S[i][max(0,j-1):min(W,j+2)].count('#')
    if i!=H-1:
      #print(i,j,'l',S[i+1][max(0,j-1):min(W,j+2)])   
      sum+=S[i+1][max(0,j-1):min(W,j+2)].count('#') 
    #print(i,j,sum)
    if S[i][j]=='.':
      R[i]+=str(sum)
    else:      
      R[i]+='#'
    
print(*R,sep='\n')

Submission status: Accepted

Solution code:
import sys
import heapq, math
from itertools import zip_longest, permutations, combinations, combinations_with_replacement
from itertools import accumulate, dropwhile, takewhile, groupby
from functools import lru_cache
from copy import deepcopy

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, 0, -1, -1]
dy = [-1, -1, -1, 0, 1, 1, 1, 0]
for h in range(H):
    for w in range(W):
        if S[h][w] == '#':
            continue
        cnt = 0
        for nx, ny in zip(dx, dy):
            x, y = w + nx, h + ny
            if x < 0 or x >= W or y < 0 or y >= H:
                continue
            if S[y][x] == '#':
                cnt += 1
        S[h][w] = str(cnt)

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

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
l = []
for i in range(h):
  s = input()
  a = []
  for j in range(w):
    a.append(s[j])
  l.append(a)
arr = []
for i in range(h):
 
  line = ''
  for j in range(w):
    if l[i][j] == "#":
        line += "#"
    else:
        k = 0
        if 0 <= i - 1 < h:
            if 0 <= j - 1 < w:
                if l[i - 1][j - 1] == "#":
                    k += 1
            if l[i - 1][j] == "#":
                k += 1
            if 0 <= j + 1 < w:
                if l[i - 1][j + 1] == "#":
                    k += 1

        if 0 <= j - 1 < w:
            if l[i][j - 1] == "#":
                k += 1
        if 0 <= j + 1 < w:
            if l[i][j + 1] == "#":
                k += 1        

        if 0 <= i + 1 < h:
            if 0 <= j - 1 < w:
                if l[i + 1][j - 1] == "#":
                    k += 1
            if l[i + 1][j] == "#":
                k += 1
            if 0 <= j + 1 < w:
                if l[i + 1][j + 1] == "#":
                    k += 1
        line += str(k)
  arr.append(line)

for e in arr:
  print(e)

Submission status: Accepted

Solution code:
h,w = map(int, input().split(" "))
board = [list(input()) for i in range(h)]
a=[['.' for i in range(w + 2)] for j in range(h + 2)]

for i in range(1, h + 1):
  for j in range(1, w + 1):
    a[i][j] = board[i-1][j-1]
#print(*a)
ans=[["" for i in range(w)] for j in range(h)]
for i in range(1, h+1):
  for j in range(1,w+1):
    if a[i][j] == '.':
      ans[i-1][j-1]=[a[i-1][j], a[i-1][j-1], a[i-1][j+1], a[i][j-1], a[i][j+1], a[i+1][j-1], a[i+1][j], a[i+1][j+1]].count('#')
    else:
      ans[i-1][j-1]='#'
for i in ans:
  print(*i,sep="")

Submission status: Accepted

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

ans=[[0]*w for i in range(h)]
s=[[""]*w for i in range(h)]
for i in range(h):
  s[i]=input()

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

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

Submission status: Accepted

Solution code:
from itertools import product

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


def num_of_mines(_i: int, _j: int) -> int:
    patterns = [
        (-1, 0), (1, 0), (0, -1), (0, 1),
        (-1, -1), (-1, 1), (1, -1), (1, 1),
    ]
    cnt = 0
    for pattern in patterns:
        y, x = _i + pattern[0], _j + pattern[1]
        if y in range(H) and x in range(W):
            c = S[y][x]
            if c == "#":
                cnt += 1
        else:
            pass
    return cnt


for i, j in product(range(H), range(W)):
    if S[i][j] == "#":
        T[i][j] = "#"
    else:
        T[i][j] = str(num_of_mines(i, j))

for column in T:
    print("".join(column))

Submission status: Accepted

Solution code:
import sys
h,w = map(int,input().split())
ls = ["0"*(w+2)]
ls += ["0" + str(input()) + "0" for _ in range(h)]
ls += ["0"*(w+2)]
di = [["0"]*w for _ in range(h)]
for i in range(1,h+1):
    for j in range(1,w+1):
        if ls[i][j] == ".":
            new = ls[i-1][j-1:j+2] + ls[i][j-1] + ls[i][j+1] + ls[i+1][j-1:j+2]
            k = new.count("#")
            k = str(k)
            di[i-1][j-1] = k
        else:
            di[i-1][j-1] = "#"
for p in range(h):
    print("".join(di[p]))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
@author: H_Hoshigi
20min 11sec
"""
# 単純に調べるだけ。
# S_listはあらかじめ一回り大きくしておく。

def main():
    H, W = map(int, input().split())
    S_lsit = ["."*(W+2)] + \
        [ ("." + input() + ".") for i in range(H)] + \
        ["."*(W+2)]

    answer_list_list = [["#" for j in range(W)] for i in range(H)]

    next8_list = [
        [1, 1],
        [1, 0],
        [1, -1],
        [0, 1],
        [0, -1],
        [-1, 1],
        [-1, 0],
        [-1, -1]
    ]

    for i in range(1, H+1):
        for j in range(1, W+1):
            if S_lsit[i][j] == ".":
                counter = 0
                for next_pair in next8_list:
                    if S_lsit[i+next_pair[0]][j+next_pair[1]] == "#":
                        counter += 1
                answer_list_list[i-1][j-1] = str(counter)

    for answer_list in answer_list_list:
        print("".join(answer_list))

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
m=[list(input()) for _ in range(h)]
ans=[[0]*w for _ in range(h)]
for i in range(h):
  for j in range(w):
    if m[i][j]=='#':
      ans[i][j]='#'
    else:
      for k in range(max(0,i-1),min(h,i+2)):
        ans[i][j]+=m[k][max(0,j-1):min(w,j+2)].count('#')
[print(*l,sep='') for l in ans]

Submission status: Accepted

Solution code:
dr = [0, 0, 1, -1, 1, -1, -1, 1]
dc = [1, -1, 0, 0, 1, 1, -1, -1]
n, m = map(int, input().split())
grid = []
for _ in range(n):
    grid.append(list(input()))
for i in range(n):
    for j in range(m):
        if grid[i][j] == '.':
            grid[i][j] = 0
for i in range(n):
    for j in range(m):
        if grid[i][j] == '#':
            for k in range(8):
                newx = i + dr[k]
                newy = j + dc[k]
                if newx < 0 or newx >= n or newy < 0 or newy >= m or grid[newx][newy] == '#':
                    continue
                grid[newx][newy] += 1
for i in range(n):
    for j in range(m):
        print(grid[i][j], end='')
    print()

Submission status: Accepted

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

for hi in range(1, H+1):
  ans = ''
  for wi in range(1, W+1):
    if S[hi][wi] == '#':
      ans += '#'
    else:
      now = 0
      for hii in [-1, 0, 1]:
        for wii in [-1, 0, 1]:
          if S[hi+hii][wi+wii] == '#':
            now += 1
      ans += str(now)
  print(ans)

Submission status: Accepted

Solution code:
h,w = map(int, input().split())
a = [list(input()) for _ in range(h)]
for i in range(h):
    for j in range(w):
        if (a[i][j]=="."):
            a[i][j] = 0
xx = [-1,-1,-1,0,0,1,1,1]
yy = [-1,0,1,-1,1,-1,0,1]
for i in range(h):
    for j in range(w):
        if (a[i][j] =="#"):
            continue
        for k in range(8):
            x = i+xx[k]
            y = j+yy[k]
            if (0<=x and x<h and 0<=y and y<w):
                if (a[x][y]=="#"):
                    a[i][j] += 1
for i in range(h):
    for j in range(w):
        if (a[i][j]!="#"):
            a[i][j] = str(a[i][j])
for i in range(h):
    print(''.join(a[i]))

Submission status: Accepted

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

for i in range(H):
    S[i] = input()

X=[[0 for j in range(W)] for i in range(H)]

for i in range(H):
    for j in range(W):
        if(S[i][j]=='#'):
            X[i][j] = -100
            if(i>0):
                if(j>0):
                    X[i-1][j-1]+=1
                X[i-1][j]+=1
                if(j<W-1):
                    X[i-1][j+1]+=1
            if(j>0):
                X[i][j-1]+=1
            if(j<W-1):
                X[i][j+1]+=1
            if(i<H-1):
                if(j>0):
                    X[i+1][j-1]+=1
                X[i+1][j]+=1
                if(j<W-1):
                    X[i+1][j+1]+=1

for i in range(H):
    for j in range(W):
        print(X[i][j] if X[i][j]>=0 else '#', end='')
    print()

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
f=[]
f.append("."*(w+2))
for i in range(h):
  f.append("."+input()+".")
f.append("."*(w+2))
a=[]
for i in range(1,h+1):
  dumy2=""
  for j in range(1,w+1):
    if f[i][j]==".":
      dumy=f[i-1][j-1]+f[i-1][j]+f[i-1][j+1]+f[i][j-1]+f[i][j]+f[i][j+1]+f[i+1][j-1]+f[i+1][j]+f[i+1][j+1]
      n=dumy.count("#")
      dumy2+=str(n)
    else:
      dumy2+="#"
  a.append(dumy2)
for i in range(h):
  print(a[i])

Submission status: Accepted

Solution code:
import numpy as np
import sys
h, w = [int(x) for x in input().split()]
s = []
for i in range(h):
  s.append([str(r) for r in list(input())])
dot = 0
for i in range(h):
  if(s[i].count('.')==0):
    dot += 1
if(dot == h):
  l = ''
  for j in range(w):
    l += '#'
  for i in range(h):
    print(l)
  sys.exit()
  
count = np.zeros((h+2,w+2))
for i in range(h):
  for j in range(w):
    if(s[i][j]=='#'):
      count[i][j] += 1
      count[i+1][j] += 1
      count[i+2][j] += 1
      count[i][j+1] += 1
      count[i][j+2] += 1
      count[i+2][j+1] += 1
      count[i+1][j+2] += 1
      count[i+2][j+2] += 1

for i in range(h):
  l = ''
  for j in range(w):
    if(s[i][j]=='#'):
      l += '#'
    else:
      l += str(int(count[i+1][j+1]))
  print(l)

Submission status: Accepted

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

for a in range(h):
    tmp = list(str(input()))
    tmp.insert(0, '+')
    tmp.append('+')
    s.append(tmp)

s.append(['+']*(w+2))

count = 0
word = ''

for a in range(1, h+1):
    for b in range(1, w+1):
        if s[a][b] == '.':
            if s[a-1][b] == '#':
                count += 1
            if s[a-1][b-1] == '#':
                count += 1
            if s[a-1][b+1] == '#':
                count += 1

            if s[a][b-1] == '#':
                count += 1
            if s[a][b+1] == '#':
                count += 1

            if s[a+1][b-1] == '#':
                count += 1
            if s[a+1][b] == '#':
                count += 1
            if s[a+1][b+1] == '#':
                count += 1
            word += str(count)
        elif s[a][b] == '#':
            word += '#'
        count = 0
    print(word)
    word = ''

Submission status: Accepted

Solution code:
h, w = map(int,input().split())
maze = []
for _ in range(h):
    maze.append(list(input()))
dx = [-1, 0, 1, -1, 1, -1, 0, 1]
dy = [-1, -1, -1, 0, 0, 1, 1, 1]
for hh in range(h):
    for ww in range(w):
        if maze[hh][ww] == "#":
            continue
        cnt = 0
        for di in range(len(dx)):
            ny = hh + dy[di]
            nx = ww + dx[di]
            if ny < 0 or ny > h-1:
                continue
            if nx < 0 or nx > w-1:
                continue
            if maze[ny][nx] == "#":
                cnt += 1
        maze[hh][ww] = str(cnt)
for i in range(h):
    print("".join(maze[i]))

Submission status: Accepted

Solution code:
# For taking integer inputs.
import math


def inp():
    return(int(input()))


# For taking List inputs.
def inlist():
    return(list(map(int, input().split())))


# For taking string inputs. Actually it returns a List of Characters, instead of a string, which is easier to use in Python, because in Python, Strings are Immutable.
def instr():
    s = input()
    return(list(s[:len(s)]))


# For taking space seperated integer variable inputs.
def invr():
    return(map(int, input().split()))


def valid(x, y): return True if x >= 0 and x < row and y >= 0 and y < col else False


fx = [+0, +0, +1, -1, -1, +1, -1, +1]
fy = [-1, +1, +0, +0, +1, +1, -1, -1]
row, col = invr()
mat = []
for _ in range(row):
    mat.append(instr())

for i in range(row):
    for j in range(col):
        if mat[i][j] == ".":
            count = 0
            for k in range(len(fx)):
                nx = i + fx[k]
                ny = j + fy[k]
                if valid(nx, ny):
                    if mat[nx][ny] == "#":
                        count += 1
            mat[i][j] = str(count)

for r in mat:
    for i in r:
        print(i, end="")
    print()

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
S = []
rng = [-1 , 0, 1]
for _ in range(H):
    S.append([0 if val == '.' else val for val in input()])

for i in range(H):
    for j in range(W):
        if S[i][j] == '#':
            for m in rng:
                tmp_i = i + m
                if tmp_i < 0:
                    continue
                for n in rng:
                    tmp_j = j + n
                    if tmp_j < 0:
                        continue
                    try:
                        S[tmp_i][tmp_j] += 1
                    except:
                        pass

for k in range(H):
    print(''.join(map(str, S[k])))

Submission status: Accepted

Solution code:

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

for _ in range(h):
    temp = input()
    s.append(temp)


def func(height, width, string):
    for i in range(height):
        for j in range(width):
            count = 0
            if string[i][j] == '.':
                if i != 0:
                    if j != 0:
                        if string[i-1][j-1] == '#':
                            count += 1
                    if string[i-1][j] == '#':
                        count += 1
                    if j != width - 1:
                        if string[i-1][j+1] == '#':
                            count += 1
                if j != 0:
                    if string[i][j-1] == '#':
                        count += 1
                if j != width - 1:
                    if string[i][j+1] == '#':
                        count += 1
                if i != height - 1:
                    if j != 0:
                        if string[i+1][j-1] == '#':
                            count += 1
                    if string[i+1][j] == '#':
                        count += 1
                    if j != width - 1:
                        if string[i+1][j+1] == '#':
                            count += 1
                if j < width:
                    s[i] = s[i][:j] + str(count) + s[i][j+1:]
                else:
                    s[i] = s[i][:j] + str(count)

    for i in range(height):
        print(string[i])


func(height=h, width=w, string=s)

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
S = []
S.append(['.' for _ in range(w+2)])
for _ in range(h):
    s = list('.' + input() + '.')
    S.append(s)
S.append(['.' for _ in range(w+2)])
for i in range(1, h+1):
    for j in range(1, w+1):
        if S[i][j] == '.':
            cnt = 0
            for p in range(i-1, i+2):
                for q in range(j-1, j+2):
                    if S[p][q] == '#':
                            cnt += 1
            S[i][j] = cnt
for i in range(1, h+1):
    ll = S[i][1:w+1]
    print(''.join([str(lll) for lll in ll]))