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=[int(i) for i in input().split()]
s=[input() for i in range(H)]

def search(h,w):
        if s[h][w]=='#':
                return '#'
        count=0
        for i in range(-1,2):
                for j in range(-1,2):
                        if 0<=h+i and h+i<H and 0<=w+j and w+j<W:
                                if i!=0 or j!=0:
                                        if s[h+i][w+j]=='#':
                                                count+=1
        return count

for h in range(H):
        for w in range(W):
                print(search(h,w),end='')
        print()

Submission status: Accepted

Solution code:
H, W = map(int, raw_input().split())
grid = [raw_input() for r in range(H)]
for r in range(H):
    line = ""
    for c in range(W):
        if grid[r][c] == "#":
            line += "#"
        else:
            cnt = 0
            for dr in range(-1, 2):
                for dc in range(-1, 2):
                    nr, nc = r+dr, c+dc
                    if (0 <= nr < H) and (0 <= nc < W) and (grid[nr][nc] == "#"):
                        cnt += 1
            line += str(cnt)
    print line

Submission status: Accepted

Solution code:
h, w = map(int, raw_input().split())
table = list()
table.append([0]*(w+2))
for _ in xrange(h):
    table.append([0]+list(map(lambda c:0 if c == "." else c, list(raw_input())))+[0])
table.append([0]*(w+2))

xy = [0, 1, 0, -1, 1, 1, -1, -1, 0]
for i in xrange(1, h+1):
    for j in xrange(1, w+1):
        if table[i][j] == "#":
            for k in xrange(8):
                if type(table[i+xy[k]][j+xy[k+1]]) == type(int()):
                    table[i+xy[k]][j+xy[k+1]] += 1


for i in xrange(1, h+1):
    print "".join(map(str, table[i][1:-1]))

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
S=[input() for i in range(H)]
for h in range(H):
        print("".join([("#" if S[h][w] == "#" else str(sum([s[max(0,w-1):min(W,w+2)].count("#") for s in S[max(0,h-1):min(H,h+2)]]))) for w in range(W)]))

Submission status: Accepted

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

for i in range(H):
    for j in range(W):
        if T[i][j] == '#':
            continue
        cnt = 0
        
        for dx in [-1, 0, 1]:
            for dy in [-1, 0, 1]:
                if not(0<=i+dy<H) or not(0<=j+dx<W):
                    continue
                if T[i+dy][j+dx] == '#':
                    cnt += 1
        T[i][j] = str(cnt)

for t in T:
    print(''.join(t))

Submission status: Accepted

Solution code:
# coding: utf-8

# 入力
h, w = map(int, input().split())

# カウント関数
def check(li, x, y):
    round_list = [[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]]
    count = 0
    num = 0
    for i, j in round_list:
        if 0 <= x + i < h and 0 <= y + j < w:
            if li[x+i][y+j] == "#":
                count += 1
    return count

# メイン処理
m = []
for i in range(h):
    m.append(list(input()))

for i in range(h):
    for j in range(w):
        if m[i][j] != "#":
            m[i][j] = check(m, i, j)

# 出力
for i in m:
    print("".join(map(str, i)))

Submission status: Accepted

Solution code:
num = [int(x) for x in input().split()]
array = []
for i in range(num[0]):
    array.append(list(input()))


for j in range(num[0]):
    for k in range(num[1]):
        cnt = 0
        if array[j][k] != "#":
            try:
                if array[j-1][k] == "#" and j-1 != -1:
                    cnt += 1
            except IndexError:
                pass
            try:
                if array[j-1][k-1] == "#" and j-1 != -1 and k-1 != -1:
                    cnt += 1
            except IndexError:
                pass
            try:
                if array[j-1][k+1] == "#" and j-1 != -1:
                    cnt += 1
            except IndexError:
                pass
            try:
                if array[j][k-1] == "#" and k-1 != -1:
                    cnt += 1
            except IndexError:
                pass
            try:
                if array[j][k+1] == "#":
                    cnt += 1
            except IndexError:
                pass
            try:
                if array[j+1][k] == "#":
                    cnt += 1
            except IndexError:
                pass
            try:
                if array[j+1][k-1] == "#" and k-1 != -1:
                    cnt += 1
            except IndexError:
                pass
            try:
                if array[j+1][k+1] == "#":
                    cnt += 1
            except IndexError:
                pass
            array[j][k] = str(cnt)

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

Submission status: Accepted

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

A = [list(input()) for i in range(H)]

for i in range(H):
	for j in range(W):
		if A[i][j] != '#':
			count = 0
			for k in range(-1,2):
				for l in range(-1,2):
					if -1 < i + k and i + k < H and -1 < j + l and j + l < W:
						if A[i+k][j+l] == '#':
							count += 1
			
			A[i][j] = str(count)

for i in A:
	print(''.join(i))

Submission status: Accepted

Solution code:
a, b = input().split()

mine = [list(input()) for i in range(int(a))]

for i in range(int(a)):
    for j in range(int(b)):
        if mine[i][j] != '#':
            count = 0
            for k in range(-1, 2):
                for l in range(-1, 2):
                    if -1 < i + k and i + k < int(a) and -1  < j + l and j + l < int(b) :
                        if mine[i+k][j+l] == '#':
                            count += 1
            mine[i][j] = count

for i in range(int(a)):
    for j in range(int(b)):
        print(mine[i][j], end='')
    print()

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
S = [list(input()) for i in range(h)]
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 not 0 <= i+dy < h or not 0 <= j+dx < w:
                    continue
                if S[i+dy][j+dx] == '#':
                    cnt += 1
        S[i][j] = str(cnt)
for s in S:
    print("".join(s))

Submission status: Accepted

Solution code:
inp = input().split(" ")
h = int(inp[0])
w = int(inp[1])

grid = []

for i in range(h):
	grid.append(list(input()))

for i in range(h):
	for j in range(w):
		c = grid[i][j]
		if c == ".":
			total = 0
			adj = []
			if i > 0:
				adj.append(grid[i-1][j])
			if j > 0:
				adj.append(grid[i][j-1])
			if i < h-1:
				adj.append(grid[i+1][j])
			if j < w-1:
				adj.append(grid[i][j+1])
			if i > 0 and j > 0:
				adj.append(grid[i-1][j-1])
			if i > 0 and j < w-1:
				adj.append(grid[i-1][j+1])
			if i < h-1 and j > 0:
				adj.append(grid[i+1][j-1])
			if i < h-1 and j < w-1:
				adj.append(grid[i+1][j+1])
			for k in adj:
				if k == "#":
					total += 1
			grid[i][j] = str(total)

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

Submission status: Accepted

Solution code:
inp = input().split(" ")
h = int(inp[0])
w = int(inp[1])

grid = []

for i in range(h):
	grid.append(list(input()))

for i in range(h):
	for j in range(w):
		c = grid[i][j]
		if c == ".":
			total = 0
			adj = []
			if i > 0:
				adj.append(grid[i-1][j])
			if j > 0:
				adj.append(grid[i][j-1])
			if i < h-1:
				adj.append(grid[i+1][j])
			if j < w-1:
				adj.append(grid[i][j+1])
			if i > 0 and j > 0:
				adj.append(grid[i-1][j-1])
			if i > 0 and j < w-1:
				adj.append(grid[i-1][j+1])
			if i < h-1 and j > 0:
				adj.append(grid[i+1][j-1])
			if i < h-1 and j < w-1:
				adj.append(grid[i+1][j+1])
			for k in adj:
				if k == "#":
					total += 1
			grid[i][j] = str(total)

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

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
b = []
temp = []
ans = []
for i in range(h):
  b.append(input())

for i in range(h):
  for j in range(w):
    count = 0
    if b[i][j] == "#":
      temp.append("#")
    else:
      # 左右
      if not j - 1 < 0:
        if b[i][j-1] == "#":
          count += 1 

      if not j + 1 >= w:
        if b[i][j+1] == "#":
          count += 1
      # 上
      if not i - 1 < 0:
        if b[i-1][j] == "#":
          count += 1
        
        if not j - 1 < 0:
          if b[i-1][j-1] == "#":
            count += 1

        if not j + 1 >= w:
          if b[i-1][j+1] == "#":
            count += 1
      
      # 下
      if not i + 1 >= h:
        if b[i+1][j] == "#":
          count += 1
        
        if not j - 1 < 0:
          if b[i+1][j-1] == "#":
            count += 1

        if not j + 1 >= w:
          if b[i+1][j+1] == "#":
            count += 1
        
      temp.append(str(count))

for i in range(h):
  print("".join(temp[i*w:i*w+w]))

Submission status: Accepted

Solution code:
import sys
def main():
    in1 = input()
    nums, length = in1.split(' ')
    nums= int(nums)
    length = int(length)
    bombs = []

    for i in range(nums):

        bombs.append(input())
    checked = [['']*length for i in range(nums)]
    for i in range(nums):
        for j in range(length):
            if bombs[i][j] == '#':
                checked[i][j] = '#'
            else:
                bombnum = 0
                if i != 0:
                    if j != 0:
                        if bombs[i-1][j-1] == '#':
                            bombnum += 1

                    if j != length -1:
                        if bombs[i-1][j+1] == '#':
                            bombnum += 1

                    if bombs[i-1][j] == '#':
                        bombnum += 1


                if j != 0:
                    if bombs[i][j-1] == '#':
                        bombnum += 1

                if j != length-1:
                    if bombs[i][j+1] == '#':
                        bombnum += 1


                if i != nums-1:
                    if j != 0:
                        if bombs[i+1][j-1] == '#':
                            bombnum += 1

                    if j != length -1:
                        if bombs[i+1][j+1] == '#':
                            bombnum += 1

                    if bombs[i+1][j] == '#':
                        bombnum += 1

                checked[i][j] = bombnum
    for i in checked:
        for j in i:
            print(j, end = '')
        print('')
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def check(b, i, j, x, y):
 if i < 0 or j < 0 or i == x or j == y:
  return 0
 if b[i][j] == "#":
  return 1
 return 0

bounds = raw_input().split(" ")
x = int(bounds[0])
y = int(bounds[1])
board = [None] * x
for i in range(0, x):
 k = raw_input()
 board[i] = [None] * y
 for j in range(0, y):
  board[i][j] = k[j]

for i in range(0, x):
 for j in range(0, y):
  if board[i][j] == ".":
   p = 0
   p += check(board, i-1, j-1, x, y)
   p += check(board, i-1, j  , x, y)
   p += check(board, i-1, j+1, x, y)
   p += check(board, i  , j-1, x, y)
   p += check(board, i  , j+1, x, y)
   p += check(board, i+1, j-1, x, y)
   p += check(board, i+1, j  , x, y)
   p += check(board, i+1, j+1, x, y)
   board[i][j] = p
 z = ""
 for j in range(0, y):
  z += str(board[i][j])
 print(z)

Submission status: Accepted

Solution code:
def check(b, i, j, x, y):
 if i < 0 or j < 0 or i == x or j == y:
  return 0
 if b[i][j] == "#":
  return 1
 return 0

bounds = raw_input().split(" ")
x = int(bounds[0])
y = int(bounds[1])
board = [None] * x
for i in range(0, x):
 k = raw_input()
 board[i] = [None] * y
 for j in range(0, y):
  board[i][j] = k[j]

for i in range(0, x):
 for j in range(0, y):
  if board[i][j] == ".":
   p = 0
   p += check(board, i-1, j-1, x, y)
   p += check(board, i-1, j  , x, y)
   p += check(board, i-1, j+1, x, y)
   p += check(board, i  , j-1, x, y)
   p += check(board, i  , j+1, x, y)
   p += check(board, i+1, j-1, x, y)
   p += check(board, i+1, j  , x, y)
   p += check(board, i+1, j+1, x, y)
   board[i][j] = p
 z = ""
 for j in range(0, y):
  z += str(board[i][j])
 print(z)

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

def search(i, j):
    global s
    count = 0
    for l in range(-1, 2):
        for m in range(-1, 2):
            if s[i+l][j+m] == '#':
                count += 1
    return str(count)

for i in range(h + 2):
    for j in range(w + 2):
        if s[i][j] == '.':
            s[i] = s[i].replace('.', search(i, j), 1)
for i in range(1, h + 1):
    print(s[i][1:-1])

Submission status: Accepted

Solution code:
# coding:utf-8
H, W = list(map(int, input().split()))
s = []
ans = []
for i in range(H):
    s.append(input())
    ans.append([])
for i in range(H):
    for j in range(W):
        if(s[i][j] == "#"):
            ans[i].append("#")
            continue
        ans[i].append(0)

for i in range(H):
	for j in range(W):
		if s[i][j] == '#':
			for h in range(-1,2):
				for k in range(-1,2):
					if h == 0 and k == 0:
						continue
					if (i == 0 and h == -1) or (i == H -1 and h == 1) or (j == 0 and k == -1) or (j == W-1 and k == 1):
						continue

					if (s[i+h][j+k]) != '#':
 						ans[i+h][j+k] += 1  
			ans[i][j] = '#'

o = ""
for i in range(H):
	for j in range(W):
		o += str(ans[i][j])
	o += "\n"
print (o)

Submission status: Accepted

Solution code:
h, w = list(map(int, input().split()))
s = []
ans = []
for i in range(h):
    s.append(input())
    ans.append([])
for i in range(h):
    for j in range(w):
        if(s[i][j] == "#"):
            ans[i].append("#")
            continue
        ans[i].append(0)
for i in range(h):
    for j in range(w):
        if(s[i][j] == "#"):
            for x in range(-1, 2):
                for y in range(-1, 2):
                    if(x == 0 and y == 0):
                        continue
                    if((i == 0 and x == -1) or (i == h - 1 and x == 1) or (j == 0 and y == -1) or (j == w - 1 and y == 1)):
                        continue
                    if(ans[i + x][j + y] != "#"):
                        ans[i + x][j + y] += 1

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

Submission status: Accepted

Solution code:
#入力
H, W = [int(i) for i in input().split()]
map = []
for i in range(H):
    line = input()
    map.append(line)

tmp = [[0 for i in range(W+2)] for j in range(H+2)]
for i in range(H):
    for j in range(W):
        if map[i][j]=='#':
            tmp[i][j]+=1
            tmp[i][j+1]+=1
            tmp[i][j+2]+=1
            tmp[i+1][j+2]+=1
            tmp[i+2][j+2]+=1
            tmp[i+2][j+1]+=1
            tmp[i+2][j]+=1
            tmp[i+1][j]+=1
            
for i in range(H):
    for j in range(W):
        if map[i][j]=='#':
            tmp[i+1][j+1]='#'
        print(str(tmp[i+1][j+1]), end='')
    print('\n')

Submission status: Accepted

Solution code:
""" minesweeper """

import re

H, W = map(int, input().split())
S = []
for _ in range(H):
    S.append(list(input()))
MINE = '#'

def get_context(h, w, field):
    # list[start:end] returns list from list[start] to list[end - 1]
    span_h = (max(0, h - 1), min(h + 1, H - 1) + 1)
    span_w = (max(0, w - 1), min(w + 1, W - 1) + 1)

    context = ''
    for row in field[span_h[0]:span_h[1]]:
        # print("row ---> {0}".format(row))
        context += ''.join(row[span_w[0]:span_w[1]])
    # print("context:{0}".format(context))
    return context

def main():
    """
    main function
    """

    """
    print(H)
    print(W)
    print(S)
    #"""

    field = S

    for h in range(H):
        for w in range(W):
            pos_char = field[h][w]
            # print(pos_char)
            if pos_char != MINE:
                context = get_context(h, w, field)
                mine_num = len(re.findall(MINE, context))
                field[h][w] = str(mine_num)

    for row in field:
        print(''.join(row))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys


def main():

    # Get Args
    args = _input_args()  # get arguments as an array from console/script parameters.

    # Call main Logic
    result = _main(args)

    # Output a result in a correct way.
    _output_result(result)


def _main(args):
    """Write Main Logic here for the contest.

    :param args: arguments
    :type args: list
    :return: result
    :rtype: depends on your logic.
    """
    # Extract arguments.
    lines = args
    H, W = int(lines[0].split()[0]), int(lines[0].split()[1])
    field_map = get_field_map(lines[1:])
    result_map = [[0 for col in range(W)] for row in range(H)]

    for h in range(H):
        for w in range(W):
            result_map[h][w] = sweep_perimeters(h, w, field_map, H, W)

    result_lines = convert_map_to_lines(result_map)

    # Return something.
    return result_lines


def sweep_perimeters(h, w, field_map, H, W):
    found_mine = 0

    if field_map[h][w] == '#':
        return '#'

    for i in range(h-1, h+1+1):
        for j in range(w-1, w+1+1):
            if (0 <= i < H) and (0 <= j < W):
                target = field_map[i][j]
                if target == '#':
                    found_mine += 1

    return found_mine


def get_field_map(lines):
    field_maps = []
    for line in lines:
        elements = list(line)
        field_maps.append(elements)
    return field_maps


def convert_map_to_lines(result_map):
    result_lines = []
    for row_array in result_map:
        stringfied_row = ''
        for value in row_array:
            value = str(value)
            stringfied_row += value
        result_lines.append(stringfied_row)

    return result_lines

def _input_args():
    # Comment-out appropriate pattern depends on subject.

    # arguments = sys.argv[1:]  # ptn1: get args from script parameters.
    # arguments = _input().split()  # ptn2: get args from 1 line console prompt with space separated.

    # for multi-line console input, use this.
    arguments = _get_args_from_multiple_lines(end_of_lines_char=[''], limit=10000000)

    # Cast elements If you need.
    # arguments = list(map(int, arguments))  # cast elements to int for example.

    return arguments  # This will be array.


def _input():
    # If Subject requires interactive input, use this and patch mock in unittest.
    return input()  # Change if necessary.


def _get_args_from_multiple_lines(end_of_lines_char=[''], limit=10000000):
    """Get arguments from multiple lines standard input.

    :param end_of_lines_char: Strings that indicate the end of lines.
    :type end_of_lines_char: list of str
    :param limit: If a number of the input line are certain, you can use this param to close prompt immediately.
    :type limit: int
    :return: args
    :rtype list of str
    """
    args = []
    for i in range(limit):
        try:
            arg = _input()
            if arg in end_of_lines_char:
                break
            args.append(arg)
        except EOFError:  # Supports EOF Style. (Very Rare case)
            break
    return args


def _output_result(result):
    # Comment-out appropriate output pattern depends on subject.

    for line in result:
        print('{}'.format(str(line)))  # Same as above, but more versatile.


if __name__ == '__main__':
    main()

Submission status: Accepted

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

H = H-1
W = W-1

res = []
for h in range(H+1):
    res_w = ""
    for w in range(W+1):
        count = 0
        if S[h][w] == "#":
            res_w += "#"
        else:
            if h - 1 >= 0:
                count += S[h - 1][w] == "#"
                if w - 1 >= 0:
                    count += S[h - 1][w - 1] == "#"
                if w + 1 <= W:
                    count += S[h - 1][w + 1] == "#"
            if h + 1 <= H:
                count += S[h + 1][w] == "#"
                if w - 1 >= 0:
                    count += S[h + 1][w - 1] == "#"
                if w + 1 <= W:
                    count += S[h + 1][w + 1] == "#"
            if w - 1 >= 0:
                count += S[h][w - 1] == "#"
            if w + 1 <= W:
                count += S[h][w + 1] == "#"
            res_w += str(count)
    res.append(res_w)

for r in res:
    print(r)

Submission status: Accepted

Solution code:
import functools as F
 
H, W = map(int, input().split())
S = F.reduce(lambda x, y: x + y, [input() for i in range(H)])
s = []
for c in S:
    s.append(0 if c == '.' else -10)
for idx, i in enumerate(s):
    if i < 0:
        if idx >= W and idx % W > 0:
            s[idx - W - 1] += 1
        if idx >= W:
            s[idx - W] += 1
        if idx >= W and idx % W < W - 1:
            s[idx - W + 1] += 1
        if idx % W > 0:
            s[idx - 1] += 1
        if idx % W < W - 1:
            s[idx + 1] += 1
        if idx + W < H * W and idx % W > 0:
            s[idx + W - 1] += 1
        if idx + W < H * W:
            s[idx + W] += 1
        if idx + W < H * W and idx % W < W - 1:
            s[idx + W + 1] += 1
 
for i in range(H):
    for j in range(W):
        print(s[j + i * W] if s[j + i * W] >= 0 else '#', end='')
    print()

Submission status: Accepted

Solution code:
import functools as F

H, W = map(int, input().split())
S = F.reduce(lambda x, y: x + y, [input() for i in range(H)])
s = []
for c in S:
    s.append(0 if c == '.' else -10)
for idx, i in enumerate(s):
    if i < 0:
        if idx >= W and idx % W > 0:
            s[idx - W - 1] += 1
        if idx >= W:
            s[idx - W] += 1
        if idx >= W and idx % W < W - 1:
            s[idx - W + 1] += 1
        if idx % W > 0:
            s[idx - 1] += 1
        if idx % W < W - 1:
            s[idx + 1] += 1
        if idx + W < H * W and idx % W > 0:
            s[idx + W - 1] += 1
        if idx + W < H * W:
            s[idx + W] += 1
        if idx + W < H * W and idx % W < W - 1:
            s[idx + W + 1] += 1

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

Submission status: Accepted

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

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

for i in range(H):
    for j in range(W):
        if S[i][j] == '#':
            for di in [-1, 0, 1]:
                for dj in [-1, 0, 1]:
                    if i + di in range(H) and j + dj in range(W):
                        X[i + di][j + dj] += 1

for i in range(H):
    w = []
    for j in range(W):
        if S[i][j] == '#':
            w.append("#")
        else:
            w.append(str(X[i][j]))
    print("".join(w))

Submission status: Accepted

Solution code:
h,w = map(int,input().split())
arr=[]
arr.append(['.']*(w+2))
for _ in range(h):
    arr.append(list('.'+input()+'.'))
arr.append(['.']*(w+2))
ans=[]
for i in range(h):
    ans.append([])
    for j in range(w):
        tmpans=0
        if arr[i+1][j+1]=='#':
            tmpans='#'
        else:
            for hh in range(3):
                for ww in range(3):
                    if not(hh==1 and ww==1) and arr[i+hh][j+ww]=='#':
                        tmpans+=1
            tmpans=str(tmpans)
        ans[i].append(tmpans)
for line in ans:
    print(''.join(line))

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
T = [","*W + ",,"]  + ["," + input() + "," for _ in range(H)] + [","*W + ",,"]
ans = ""
d = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]
for i in range(1, H+1):
    for j in range(1, W+1):
        if T[i][j] == "#":
            ans += "#"
        else:
            ans += str(sum(T[i+x][j+y] == "#" for x, y in d))
    ans += "\n"
print(ans)

Submission status: Accepted

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

def count(S,i,j):
    if i >= 0 and i < H and j >= 0 and j < W:
        if S[i][j] != '#':
            S[i][j] += 1

H, W = map(int, raw_input().split())
S = [['' for i in range(W)] for j in range(H)]
mine = []
for h in range(H):
    tmps = raw_input()
    for index,tmp in enumerate(tmps):
        if tmp == '#':
            S[h][index] = '#'
        else:
            S[h][index] = 0
for i,a in enumerate(S):
    for j,b in enumerate(a):
        if b == '#':
            count(S,i,j+1)
            count(S,i,j-1)
            count(S,i-1,j-1)
            count(S,i-1,j)
            count(S,i-1,j+1)
            count(S,i+1,j-1)
            count(S,i+1,j)
            count(S,i+1,j+1)
for s in S:
    p = ''
    for q in s:
        p = p + str(q)
    print(p)

Submission status: Accepted

Solution code:
#!/usr/bin/python

from sys import stdin

def count(S, i, j):
  c = 0
  for y in range(i - 1, i + 2):
    for x in range(j - 1, j + 2):
      if 0 <= y < len(S) and 0 <= x < len(S[y]) and S[y][x] == '#':
        c += 1
  return str(c)

def solve(S):
  return [[count(S, i, j) if S[i][j] == '.' else '#'
          for j in range(len(S[i]))] for i in range(len(S))]

H, W = [int(w) for w in stdin.readline().split()]
S = []
for i in range(H):
  S.append(stdin.readline().strip())
R = solve(S)
R = '\n'.join([''.join(r) for r in R])
print(R)

Submission status: Accepted

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

ans = []
for i in S:
    ans.append(list(i))

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 S[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 S[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:
H, W = list(map(int, input().split()))
S = []
for _ in range(H):
    S.append(list(input()))

if H > 1:
    for w in range(W):
        if S[0][w] == ".":
            S[0][w] = str(S[0][max(0,w-1):min(W, w+2)].count("#")
                        +S[1][max(0,w-1):min(W, w+2)].count("#"))

    for h in range(1, H-1):
        for w in range(W):
            if S[h][w] == ".":
                S[h][w] = str(S[h-1][max(0,w-1):min(W, w+2)].count("#")
                            +S[h][max(0,w-1):min(W, w+2)].count("#")
                            +S[h+1][max(0,w-1):min(W, w+2)].count("#"))

    for w in range(W):
            if S[H-1][w] == ".":
                S[H-1][w] = str(S[H-2][max(0,w-1):min(W, w+2)].count("#")
                            +S[H-1][max(0,w-1):min(W, w+2)].count("#"))

else:
    for w in range(W):
        if S[0][w] == ".":
            S[0][w] = str(S[0][max(0,w-1):min(W, w+2)].count("#"))
for h in range(H):
    print("".join(S[h]))

Submission status: Accepted

Solution code:


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

def bom_count(S, x, y):
    dx = [-1,-1,-1,0,0,0,1,1,1]
    dy = [-1,0,1,-1,0,1,-1,0,1]
    cnt = 0
    for i in range(len(dx)):
        if 0 <= x + dx[i] < H and 0 <= y + dy[i] < W and S[x + dx[i]][y + dy[i]] == '#':
            cnt += 1
    return str(cnt);


for x in range(H):
    for y in range(W):
        if S[x][y] != '.':
            continue
        S[x][y] = bom_count(S, x, y)

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

Submission status: Accepted

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

a=[['.' for x in range(w+2)]]

for i in range(h):
    b=list(str(input()))
    b= ['.']+b+['.']
    a.append(b)

footer=['.' for x in range(w+2)]
a.append(footer)
    

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

            ans += str(count)

    print(ans)

Submission status: Accepted

Solution code:
HM = input().split()
H, M = [int(HM[i]) for i in range(len(HM))]

S = [input() for i in range(H)]
#print(S)
#print(T[0][1])
#S2 = list([S[i] for i in range(H)] for j in range(M))
S2 = []
for i in range(H):
    S2.append(list(S[i]))
#print(S2)

def minesweeper():
    for i in range(H):
        for j in range(M):
            if S[i][j] == ".":
                c = count(i, j)
                #print(c)
                S2[i][j] = c
    for i in range(H):
        for j in range(M-1):
            print(S2[i][j], end="")
        print(S2[i][M-1])
    return 0


def count(x,y):
    c = 0
    #print("x={}".format(x))
    if (x >= 1 and y >= 1):
        if S[x-1][y-1] == '#':
            c += 1
            #print('1')
    if (x >= 1):
        if S[x-1][y] == "#":
            c += 1
            #print('2')
    if x >= 1 and y <= M - 2:
        if S[x-1][y+1] == "#":
            c += 1
            #print("x={}".format(x))
            #print('3')
    if (y >= 1):
        if S[x][y-1] == "#":
            c += 1
            #print('4')
    if (y <= M - 2):
        if S[x][y+1] == "#":
            c += 1
            #print('5')
    if (x <= H-2 and y >= 1):
        if S[x+1][y-1] == "#":
            c += 1
            #print('6')
    if (x <= H-2):
        if S[x+1][y] == "#":
            c += 1
            #print('7')
    if (x <= H-2 and y <= M-2):
        if S[x+1][y+1] == "#":
            c += 1
            #print('8')
    return c

minesweeper()