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:
#https://atcoder.jp/contests/abc075/tasks/abc075_b?lang=ja
H, W = map(int, input().split())
s = [list(input()) for _ in range(H)]
for i in range(H):
    for j in range(W):
        count = 0
        if s[i][j] == "#":
            pass
        else:
            if i > 0 and j > 0 and s[i-1][j-1] == "#": #左上
                count +=1
            if i > 0 and s[i-1][j]=="#": #上
                count +=1
            if i > 0 and j <W-1 and s[i-1][j+1] =="#": #右上
                count +=1  
            if j < W-1 and s[i][j+1] =="#": #右
                count +=1
            if i < H-1 and j<W-1 and s[i+1][j+1] =="#": #右下
                count +=1
            if i < H-1 and s[i+1][j] =="#": #下
                count +=1
            if i<H-1 and j>0 and s[i+1][j-1] =="#":  #左下
                count +=1
            if j > 0 and s[i][j-1] == "#":   #左
                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())

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

H,W = map(int, input().split())
s = [list("."+input()+".") for _ in range(H)]
S = [["."]*(W+2)] + s + [["."]*(W+2)]
T = copy.deepcopy(S)

for i in range(1,H+1):
    for j in range(1,W+1):
        cnt = S[i-1][j-1:j+2].count('#')+S[i][j-1].count('#')
        cnt += S[i][j+1].count('#')+S[i+1][j-1:j+2].count('#')
        if T[i][j]!="#":
            T[i][j] = str(cnt)

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

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
M=[['.']*(w+2),['.']*(w+2)]
for i in range(h):
    m=list(input())
    m.append('.')
    m.insert(0,'.')
    M.insert(-1,m)
K=[]

for i in range(1,h+1):
    k=[]
    for j in range(1,w+1):
        if M[i][j]=='#':
            k.append('#')
        else:
            c=0
            for r in range(j-1,j+2):
                if M[i-1][r]=='#':
                    c+=1
            for r in range(j-1,j+2):
                if M[i+1][r]=='#':
                    c+=1
            if M[i][j-1]=='#':
                c+=1
            if M[i][j+1]=='#':
                c+=1
            k.append(str(c))
    K.append(k)
for i in range(len(K)):
    print(''.join(K[i]))

Submission status: Accepted

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

def inside(x, y):
    return 0 <= x < h and 0 <= y < w

for i in range(h):
    for j in range(w):
        if s[i][j] == '#':
            continue
        cnt = 0
        for dx in [-1,0,1]:
            for dy in [-1,0,1]:
                if dx == 0 and dy == 0:
                    continue
                x, y = i + dx, j + dy
                if not inside(x, y):
                    continue
                if s[x][y] == '#':
                    cnt += 1
        res[i][j] = str(cnt)

for l in res:
    print(*l, sep = '')

Submission status: Accepted

Solution code:
import itertools

H, W = map(int, input().split())
S = [[0]*W for _ in range(H)]
for h in range(H):
    s = input()
    for w in range(W):
        if s[w] == '#':
            S[h][w] = '#'

for i, j in itertools.product(range(H), range(W)):
    if S[i][j] == '#':
        if j != 0 and S[i][j-1] != '#':
            S[i][j-1] += 1
        if j != W - 1 and S[i][j+1] != '#':
            S[i][j+1] += 1
        if i != 0 and S[i-1][j] != '#':
            S[i-1][j] += 1
        if i != H-1 and S[i+1][j] != '#':
            S[i+1][j] += 1

        if j != 0 and i != 0 and S[i-1][j-1] != '#':
            S[i-1][j-1] += 1
        if j != W - 1 and i != H - 1 and S[i+1][j+1] != '#':
            S[i+1][j+1] += 1
        if i != 0 and j != W - 1 and S[i-1][j+1] != '#':
            S[i-1][j+1] += 1
        if i != H-1 and j != 0 and S[i+1][j-1] != '#':
            S[i+1][j-1] += 1

for s in S:
    print(*s, sep='')

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
S = [list(input()) for _ in range(H)]
for i in range(H):
	for j in range(W):
		if S[i][j] == ".":
			cnt = 0
			if i != 0:
				cnt += S[i - 1][max(0, j - 1): min(j + 1, W - 1) + 1].count("#")
			cnt += S[i][max(0, j - 1): min(j + 1, W - 1) + 1].count("#")
			if i != H - 1:
				cnt += S[i + 1][max(0, j - 1): min(j + 1, W - 1) + 1].count("#")
			S[i][j] = str(cnt)
for x in range(H):
	print("".join(S[x]))

Submission status: Accepted

Solution code:
def main():
    h, w = map(int, input().split())
    grid = []
    for height in range(0, h):
        grid.append(list(input()))

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

    for height in range(0, h):
        for width in range(0, w):
            if grid[height][width] == '#':
                continue
            else:
                grid[height][width] = 0

            for i in range(0, 8):
                if (height + dy[i] < 0) or (height + dy[i] >= h) or (width + dx[i] < 0) or (width + dx[i] >= w):
                    continue
                if (grid[height + dy[i]][width + dx[i]]) == '#':
                    grid[height][width] += 1

    for height in range(0, h):
        for width in range(0, w):
            print(grid[height][width], end='')
        print()


if __name__ == "__main__":
  main()

Submission status: Accepted

Solution code:
def main():
    h, w = map(int, input().split())
    grid = []
    for height in range(0, h):
        grid.append(list(input()))

    replaced = []
    for height in range(0, h):
        replaced.append([0] * w)

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

    for height in range(0, h):
        for width in range(0, w):
            if grid[height][width] == '#':
                replaced[height][width] = '#'
                continue
            for i in range(0, 8):
                if (height + dy[i] < 0) or (height + dy[i] >= h) or (width + dx[i] < 0) or (width + dx[i] >= w):
                    continue
                if (grid[height + dy[i]][width + dx[i]]) == '#':
                    replaced[height][width] += 1

    for height in range(0, h):
        for width in range(0, w):
            print(replaced[height][width], end='')
        print()


if __name__ == "__main__":
  main()

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
S=[['.']*(W+2),['.']*(W+2)]
for i in range(H):
    s=list(input())
    s.insert(0,'.')
    s.append('.')
    S.insert(-1,s)
X=[]

for k in range(1,H+1):
    x=[]
    for h in range(1,W+1):
        if S[k][h]=='#':
            x.append('#')
        else:
            a=0
            for g in range(3):
                if S[k-1][h-1+g]=='#':
                    a+=1
            if S[k][h-1]=='#':
                a+=1
            if S[k][h+1]=='#':
                a+=1
            for g in range(3):
                if S[k+1][h-1+g]=='#':
                    a+=1
            x.append(str(a))
    X.append(x)
    
for i in X:
    print(''.join(i))

Submission status: Accepted

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

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

for i in range(1,h+1):
    for j in range(1,w+1):
        c=''
        if s[i][j]!='#':
            for x,y in zip(dx,dy):
                c+=s[i+x][j+y]
            s[i][j]=str(c.count('#'))
for i in range(1,h+1):
    print(''.join(s[i][1:-1]))
# mixed
# 提出 #5372018
# https://img.atcoder.jp/abc075/editorial.pdf

Submission status: Accepted

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

list1 = []
moziretu = ""

for i in range(h):
    s = input()
    moziretu = list(s.replace(".", "0").replace(".", "9"))
    moziretu = [int(c) if c.isdecimal() else c for c in moziretu]
    list1.append(moziretu)
    
for i in range(h):
    for j in range(w):
        if list1[i][j] == "#":
            try:
                if i-1 >= 0 and j-1 >= 0:
                    list1[i-1][j-1] += 1
            except:
                pass
            try:
                if i-1 >= 0:
                    list1[i-1][j] += 1
            except:
                pass
            try:
                if i-1 >= 0:
                    list1[i-1][j+1] += 1
            except:
                pass
            try:
                if j-1 >= 0:
                    list1[i][j-1] += 1
            except:
                pass            
            try:
                list1[i][j+1] += 1
            except:
                pass            
            try:
                if j-1 >= 0:
                    list1[i+1][j-1] += 1
            except:
                pass            
            try:
                list1[i+1][j] += 1
            except:
                pass            
            try:
                list1[i+1][j+1] += 1
            except:
                pass
            
for i in range(h):
    for j in range(w):
        try:
            list1[i][j] = str(list1[i][j])
        except:
            pass

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

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
S=["."]*(W+2)
S=[["."]*(W+2)] + [list("."+input()+".") for _ in range(H)] + [["."]*(W+2)]
for i in range(1,H+1):
    for j in range(1,W+1):
        if S[i][j] == "#":
            print("#",end="")
        else:
            print((S[i-1][j-1]+S[i-1][j]+S[i-1][j+1]+S[i][j-1]+S[i][j+1]+S[i+1][j-1]+S[i+1][j]+S[i+1][j+1]).count("#"),end="")
    print()

Submission status: Accepted

Solution code:
def findbomb(x,y,H,W):
    bombnum=0
    #up
    if x!=0:
        bombnum+=(table[x-1][y]=="#")
        if y!=0:
            bombnum+=(table[x-1][y-1]=="#")
        if y!=W-1:
            bombnum+=(table[x-1][y+1]=="#")
    #side
    if y!=0:
        bombnum+=(table[x][y-1]=="#")
    if y!=W-1:
        bombnum+=(table[x][y+1]=="#")
    #bottom
    if x!=H-1:
        bombnum+=(table[x+1][y]=="#")
        if y!=0:
            bombnum+=(table[x+1][y-1]=="#")
        if y!=W-1:
            bombnum+=(table[x+1][y+1]=="#")
    return(bombnum)
H,W=map(int,input().split())
table=[]
for i in range(H):
    table.append(list(input()))
result=[[0]*W for hoge in range(H)]

for x,row in enumerate(table):
    for y,b in enumerate(row):
        if b=="#":result[x][y]="#"
        else:result[x][y]=findbomb(x,y,H,W)
for t in result:
    print(*t,sep="")

Submission status: Accepted

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

for i in range(1, h+1):
  for j in range(1, w+1):
    if s[i][j] != "#":
      c = [s[i-1][j-1], s[i-1][j], s[i-1][j+1], s[i][j-1], s[i][j+1], s[i+1][j-1], s[i+1][j], s[i+1][j+1]]
      s[i][j] = str(c.count("#"))
      
for i in range(1,h+1):
  print("".join(s[i][1:-1]))

Submission status: Accepted

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

ans = []
for i in range(1, h+1):
  for j in range(1, w+1):
    if s[i][j] == "#":
      ans.append("#")
    else:
      c = [s[i-1][j-1], s[i-1][j], s[i-1][j+1], s[i][j-1], s[i][j+1], s[i+1][j-1], s[i+1][j], s[i+1][j+1]]
      ans.append(c.count("#"))
      
for i in range(h):
  print("".join(list(map(str, ans[i*w:(i+1)*w]))))

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
lists = []
cnt = 0
for i in range(H):
    S = list(str(input()))
    lists.append(S)
for i in range(H):
    for j in range(W):
        if lists[i][j] == ".":
            lists[i][j] = 0
        elif lists[i][j] == "#":
            cnt += 1
if cnt == (H*W):
    for i in range(H):
        print("".join(lists[i]))
    exit()
for i in range(H):
    for j in range(W):
        if lists[i][j] == "#":
            if i > 0:
                if lists[i-1][j] != "#":
                    lists[i-1][j] += 1
            if j > 0:
                if lists[i][j - 1] != "#":
                    lists[i][j-1] += 1
            if i < H and i != (H-1):
                if lists[i+1][j] != "#":
                    lists[i+1][j] += 1
            if j < W and j != (W-1):
                if lists[i][j+1] != "#":
                    lists[i][j+1] += 1
            if i > 0 and j < W and j != (W-1):
                if lists[i-1][j+1] != "#":
                    lists[i-1][j+1] += 1
            if j > 0 and i < H and i != (H-1):
                if lists[i+1][j-1] != "#":
                    lists[i+1][j-1] += 1
            if i > 0 and j > 0:
                if lists[i-1][j-1] != "#":
                    lists[i-1][j-1] += 1
            if i < H and j <W and j != (W-1) and i != (H-1):
                if lists[i+1][j+1] != "#":
                    lists[i+1][j+1] += 1
str_list = []
for i in range(H):
    m = map(str,lists[i])
    mojiretsu = "".join(m)
    print(mojiretsu)

Submission status: Accepted

Solution code:
h, w = [int(i) for i in input().split()]
s = ["."*(w+2)]
for hi in range(h):
  s.append("." + input() + ".")
s.append("."*(w+2))
ans = [""] * h
for hi in range(1,h+1):
  for wi in range(1,w+1):
    if s[hi][wi] == ".":
      ans[hi-1] += str((s[hi-1][wi-1:wi+2]+s[hi][wi-1]+s[hi][wi+1]+s[hi+1][wi-1:wi+2]).count("#"))
    else:
      ans[hi-1] += "#"
for hi in range(h):
  print(ans[hi])

Submission status: Accepted

Solution code:
n, b = (int(i) for i in input().split())  
l = [input() for i in range(n)] 
z = [-1,0,1]

for i in range(n):
  for ii in range(b):
    if l[i][ii] == "#":
      print("#",end="")
    else:
      print(sum([l[x+i][xx+ii] == "#" for x in z for xx in z if 0 <= x+i < n and 0 <= xx+ii < b]),end="")
  print("")

Submission status: Accepted

Solution code:
H,W = [int(x) for x in input().split()]
S = ['.'*(W+2)]+['.'+input()+'.' for _ in range(H)]+['.'*(W+2)]
ans = []
for i in range(1,H+1):
    s = ''
    for j in range(1,W+1):
        cnt = 0
        li = [[-1,-1],[0,-1],[1,-1],[-1,0],[1,0],[-1,1],[0,1],[1,1]]
        for x in li:
            if(S[i+x[0]][j+x[1]]=='#'):
                cnt += 1
        if(S[i][j]=='#'):
            s+='#'
        else:
            s+=str(cnt)

    ans.append(s)
for i in ans:
    print(i)

Submission status: Accepted

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

for i in range(H):
    for j in range(W):
        if S[i][j] == ".":
            cnt = 0
            for di in [-1,0,1]:
                for dj in [-1,0,1]:
                    if di == 0 and dj == 0:
                        continue
                    ni = i + di; nj = j + dj
                    if not(0 <= ni <= H-1 and 0 <= nj <= W-1):
                        continue
                    if S[ni][nj] == "#":
                        cnt += 1
            S[i][j] = str(cnt)

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

Submission status: Accepted

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

def solve():
    H, W = list(map(int, input().split()))
    S = [None] * H

    for i in range(H):
        S[i] = input()
    
    ans = [["#" for w in range(W)] for h in range(H)]
    for h in range(H):
        for w in range(W):
            if S[h][w] == ".":
                bomb = 0
                if w-1 >= 0 and h-1 >= 0:
                    if S[h-1][w-1] == "#":
                        bomb += 1
                if h-1 >= 0:
                    if S[h-1][w] == "#":
                        bomb += 1
                if h-1 >= 0 and w+1 < W:
                    if S[h-1][w+1] == "#":
                        bomb += 1
                if w-1 >= 0:
                    if S[h][w-1] == "#":
                        bomb += 1
                if w+1 < W:
                    if S[h][w+1] == "#":
                        bomb += 1
                if h+1 < H and w-1 >= 0:
                    if S[h+1][w-1] == "#":
                        bomb += 1
                if h+1 < H:
                    if S[h+1][w] == "#":
                        bomb += 1
                if h+1 < H and w+1 < W:
                    if S[h+1][w+1] == "#":
                        bomb += 1
                ans[h][w] = bomb
    
    for h in range(H):
        for w in range(W):
            print(ans[h][w], end="")
        print()

if __name__ == "__main__":
    solve()

Submission status: Accepted

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

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

dict = (
    (-1, -1),
    (-1, 0),
    (-1, 1),
    (0, -1),
    (0, 1),
    (1, -1),
    (1, 0),
    (1, 1),
)

for i in range(h):
    for j in range(w):
        t = grid[i][j]
        if t == '#':
            continue

        for dy, dx in dict:
            y = i - dy
            x = j - dx
            if y >= 0 and h > y and x >= 0 and w > x:
                z = grid[y][x]
                if z == '#':
                    grid[i][j] += 1

answer = '\n'.join(map(lambda el: ''.join(map(str, el)), grid))
print(answer)

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
s=[[x for x in input()] for _ in range(h)]
for i in range(h):
    for j in range(w):
        if s[i][j] =='#':
            continue
        cnt=0
        for k in range(-1,2):
            if i+k<0 or i+k>=h:
                continue
            for l in range(-1,2):
                if j+l<0 or j+l>=w:
                    continue 
                if s[i+k][j+l]=='#':
                    cnt+=1
        s[i][j]=str(cnt)
for i in range(h):
    print(''.join(s[i]))

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
S=[[-9999 if s == "#" else 0 for s in input()] for _ in range(H)]
for h in range(H):
	for w in range(W):
		if S[h][w] < 0:
			for xh in range(max(0, h-1), min(H, h+2)):
				for xw in range(max(0, w-1), min(W, w+2)):
					if xh != h or xw != w:
						S[xh][xw] += 1
print("\n".join(["".join(["#" if x < 0 else str(x) for x in row]) for row in S]))

Submission status: Accepted

Solution code:
import numpy as np
H, W = map(int, input().split())
m = np.zeros((H,W))
bomb = []
for h in range(H):
  row = list(str(input()))
  for w in range(W):
    if row[w] == "#":
      bomb.append((h, w))

for h, w in bomb:
  if h!=0 and w!=0:
    m[h-1, w-1] += 1
  if h!=0:
    m[h-1, w] += 1
  if h!=0 and w!=W-1:
    m[h-1, w+1] += 1
    
  if w!=0:
    m[h, w-1] += 1
  if w!=W-1:
    m[h, w+1] += 1
  
  if h!=H-1 and w!=0:
    m[h+1, w-1] += 1
  if h!=H-1:
    m[h+1, w] += 1
  if h!=H-1 and w!=W-1:
    m[h+1, w+1] += 1

for h in range(H):
  for w in range(W):
    if (h, w) in bomb:
      print("#", end="")
    else:
      print(int(m[h, w]), end="")
  print("", end="\n")

Submission status: Accepted

Solution code:
tmp = (input().split(" "))
H = int(tmp[0])
W = int(tmp[1])

datas = [input() for i in range(0, H, 1)]

array = []

for data in datas:
  tmp = [x for x in list(data)]
  array.append(tmp)

for i in range(0, H, 1):
  for j in range(0, W, 1):
    
    cnt = 0
    
    #空きマスでない場合
    if array[i][j] == "#":
      continue
      
    else:

      for l in range(-1, 2, 1):
        for m in range(-1, 2, 1):
                
          no1 = i + l
          no2 = j + m

          if i == no1 and j == no2:
            continue

          try:

            if no1 < 0 or no2 < 0:
              continue
              
            else:
              if array[no1][no2] == "#":
                cnt += 1
              else:
                pass
            
          except:
            pass
          
      array[i][j] = str(cnt)
      
for x in (array):
  print("".join(x))

Submission status: Accepted

Solution code:
from collections import deque

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

for i in range(h):
  for j in range(w):
    if hw[i][j] == ".":
      cnt = 0
      for x in [-1, 0, 1]:
        for y in [-1, 0, 1]:
          if i+y in range(h) and j+x in range(w):
            if hw[i+y][j+x]=="#":
              cnt += 1
      hw[i][j]=cnt

for line in hw:
  print("".join(list(map(str, line))))

Submission status: Accepted

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

def wrap(S):
    return [row + ["."] for row in S] + [["."]*(W+1)]

S2 = wrap(S)
ans = [""]*(H)
for i in range(H):
    for j in range(W):
        if S2[i][j] == "#":
            ans[i] += "#"
        else:
            cnt = 0
            for di in (-1,0,1):
                for dj in (-1,0,1):
                    cnt += int(S2[i+di][j+dj] == "#")
            ans[i] += str(cnt)

for out in ans:
    print(out)

Submission status: Accepted

Solution code:


H,W = map(int, input().split())
Sn = [["." for i in range(W+2)]]
for _ in range(H):
  Sn.append(["."]+list(str(input()))+["."])
Sn.append(["." for i in range(W+2)])

for i in range(1,H+1):
  for j in range(1,W+1):
    if Sn[i][j] == '#':
      continue
    l = [Sn[i-1][j-1], Sn[i-1][j], Sn[i-1][j+1], Sn[i][j-1], Sn[i][j+1], Sn[i+1][j-1], Sn[i+1][j], Sn[i+1][j+1]]
    Sn[i][j] = str(l.count('#'))

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

Submission status: Accepted

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

for i in range(h):
    for j in range(w):
        if s[i][j] == '#':
            ans[i][j] = '#'
        else:
            count = 0
            for k in temp:
                i_temp, j_temp = i+k[0], j+k[1]
                if 0 <= i_temp < h and 0 <= j_temp < w:
                    if s[i_temp][j_temp] == '#':
                        count += 1
            ans[i][j] = count
    print(*ans[i], sep='')

Submission status: Accepted

Solution code:

def read_input():
    h, w = map(int, input().split())
    slist = []
    for i in range(h):
        slist.append(input().strip())

    return h, w, slist

# i, jの周辺に1を足す
def sumup(board, i, j):
    def notbomb(x):
        return x != '#'

    up = i - 1 >= 0
    down = i + 1 < len(board)
    left = j - 1 >= 0
    right = j + 1 < len(board[0])

    if up:
        if notbomb(board[i - 1][j]):
            board[i - 1][j] += 1
        if left:
            if notbomb(board[i - 1][j - 1]):
                board[i - 1][j - 1] += 1
        if right:
            if notbomb(board[i - 1][j + 1]):
                board[i - 1][j + 1] += 1
    if left:
        if notbomb(board[i][j - 1]):
            board[i][j - 1] += 1
    if right:
        if notbomb(board[i][j + 1]):
           board[i][j + 1] += 1
    if down:
        if notbomb(board[i + 1][j]):
            board[i + 1][j] += 1
        if left:
            if notbomb(board[i + 1][j - 1]):
                board[i + 1][j - 1] += 1
        if right:
            if notbomb(board[i + 1][j + 1]):
                board[i + 1][j + 1] += 1
    return board

def submit():
    h, w, slist = read_input()

    board = []
    for s in slist:
        board.append([0 if c == '.' else c for c in s])

    for i in range(h):
        for j in range(w):
            if board[i][j] == '#':
                board = sumup(board, i, j)

    for row in board:
        print(''.join([str(c) for c in row]))


if __name__ == '__main__':
    submit()

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
S = [list(input()) for i in range(h)]
U = [-1, 0]
L = [0, -1]
D = [1, 0]
R = [0, 1]
UL = [-1, -1]
UR = [-1, 1]
DL = [1, -1]
DR = [1, 1]
direction = [U,D,L,R,UL,UR,DL,DR]
for i in range(h):
    for j in range(w):
        count = 0
        if S[i][j] == ".":
            for d in direction:
                x, y = d
                if h > i+x >= 0 and w > j+y >= 0:
                    if S[i+x][j+y] == "#":
                        count += 1
            S[i][j] = count
for i in range(h):
    print(*S[i], sep='')

Submission status: Accepted

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

for i in S:
    i.insert(0, 0)
    i.append(0)

zero_ls = [i for i in range(W+2)]
S.insert(0, zero_ls)
S.append(zero_ls)

for i in range(1, H+1):
    for j in range(1, W+1):
        if S[i][j] == '#':
            if S[i-1][j] != '#':  # top_center
                S[i-1][j] += 1
            if S[i-1][j-1] != '#':  # top_left
                S[i-1][j-1] += 1
            if S[i-1][j+1] != '#':  # top_right
                S[i-1][j+1] += 1
            if S[i][j-1] != '#':  # mid_left
                S[i][j-1] += 1
            if S[i][j+1] != '#':  # mid_right
                S[i][j+1] += 1
            if S[i+1][j] != '#':  # bottom_center
                S[i+1][j] += 1
            if S[i+1][j-1] != '#':  # bottom_left
                S[i+1][j-1] += 1
            if S[i+1][j+1] != '#':  # bottom_right
                S[i+1][j+1] += 1

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

Submission status: Accepted

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

for i in range(H):
    for j in range(W):
        count = 0
        if S[i][j] != '#':
            if i-1 >= 0:
                if S[i-1][j] == '#':  # top
                    count += 1
                if j-1 >= 0 and S[i-1][j-1] == '#':  # top_left
                    count += 1
                if j+1 < W and S[i-1][j+1] == '#':  # top_right
                    count += 1
            if j-1 >= 0 and S[i][j-1] == '#':  # mid_left
                count += 1
            if j+1 < W and S[i][j+1] == '#':  # mid_right
                count += 1
            if i+1 < H:
                if S[i+1][j] == '#':  # bottom_center
                    count += 1
                if j-1 >= 0 and S[i+1][j-1] == '#':  # bottom_left
                    count += 1
                if j+1 < W and S[i+1][j+1] == '#':  # bottom_right
                    count += 1
            S[i][j] += count

for row in S:
    for s in row:
        print(s, end="")
    print()

Submission status: Accepted

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

for i in range(H):
    for j in range(W):
        if S[i][j] == '#':
            if i-1 >= 0:  # top
                if S[i-1][j] != '#':
                    S[i-1][j] += 1
                if j-1 >= 0 and S[i-1][j-1] != '#':  # left
                    S[i-1][j-1] += 1
                if j+1 < W and S[i-1][j+1] != '#':  # right
                    S[i-1][j+1] += 1
            if j-1 >= 0 and S[i][j-1] != '#':  # mid_left
                S[i][j-1] += 1
            if j+1 < W and S[i][j+1] != '#':  # mid_right
                S[i][j+1] += 1
            if i+1 < H:  # bottom
                if S[i+1][j] != '#':
                    S[i+1][j] += 1
                if j-1 >= 0 and S[i+1][j-1] != '#':  # left
                    S[i+1][j-1] += 1
                if j+1 < W and S[i+1][j+1] != '#':  # right
                    S[i+1][j+1] += 1

for row in S:
    for s in row:
        print(s, end="")
    print()

Submission status: Accepted

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

s = [["." for _ in range(w + 2)]] + [["."] + list(input()) + ["."] for _ in range(h)] + [["." for _ in range(w + 2)]]

for r in range(1, h + 1):
    for c in range(1, w + 1):
        if s[r][c] == ".":
            s[r][c] = str([s[r + dr][c + dc] for dr in [-1, 0, 1] for dc in [-1, 0, 1]].count("#"))

for r in range(1, h + 1):
    print("".join(s[r][1: w+1]))

Submission status: Accepted

Solution code:
from functools import reduce
import math

def main():
    # 文字列の2進数を数値にする
    # '101' → '5'
    # 文字列の頭に'0b'をつけてint()にわたす
    # binary = int('0b'+'101',0)

    # 2進数で立っているbitを数える
    # 101(0x5) → 2
    # cnt_bit = bin(5).count('1')
    
    # N! を求める
    # f = math.factorial(N)

    # N の逆元
    # N_inv = pow(N,MOD-2,MOD)

    # nCr
    # Nの階乗 * rの階乗の逆元 * n-rの階乗の逆元
    
    # 切り捨て
    # 4 // 3
    # 切り上げ
    #-(-4 // 3)
    
    # 初期値用:十分大きい数(100億)
    INF = float("inf")

    # 大きな素数
    MOD = 10**9+7
    
    # 1文字のみを読み込み
    # 入力:2
    # a = input().rstrip()
    # 変数:a='2'
    
    # スペース区切りで標準入力を配列として読み込み
    # 入力:2 4 5 7
    # a, b, c, d = (int(_) for _ in input().split())  
    # 変数:a=2 b=4 c=5 d =7
    
    # 1文字ずつ標準入力を配列として読み込み
    # 入力:2 4 5 7
    # a = list(int(_) for _ in input().split())
    # 変数:a = [2, 4, 5, 7]    

    # 1文字ずつ標準入力を配列として読み込み
    # 入力:2457
    # a = list(int(_) for _ in input())
    # 変数:a = [2, 4, 5, 7]    
    H,W = (int(_) for _ in input().split())
    S = []
    V = [(0,1),(0,-1),(1,0),(-1,0),(1,1),(1,-1),(-1,1),(-1,-1)]
    
    for i in range(H):
        S.append(list(_ for _ in input()))
        
    for h in range(H):
        for w in range(W):
            cnt = 0
            if(S[h][w] == '.'):                
                for v in V:
                    if(h+v[0]<H and h+v[0]>=0 and w+v[1]<W and w+v[1]>=0 and S[h+v[0]][w+v[1]]=='#'):
                        cnt += 1
                S[h][w] = cnt
                        
    for h in range(H):
        print(''.join(str(_) for _ in S[h]))
    
if __name__ == '__main__':
    main()