Problem:


Score: 300 points

Problem Statement

We have a canvas divided into a grid with H rows and W columns. The square at the i-th row from the top and the j-th column from the left is represented as (i, j).

Initially, all the squares are white. square1001 wants to draw a picture with black paint. His specific objective is to make Square (i, j) black when s_{i, j}= #, and to make Square (i, j) white when s_{i, j}= ..

However, since he is not a good painter, he can only choose two squares that are horizontally or vertically adjacent and paint those squares black, for some number of times (possibly zero). He may choose squares that are already painted black, in which case the color of those squares remain black.

Determine if square1001 can achieve his objective.  

Constraints

H is an integer between 1 and 50 (inclusive).

W is an integer between 1 and 50 (inclusive).

For every (i, j) (1 \leq i \leq H, 1 \leq j \leq W), s_{i, j} is # or ..

Input

Input is given from Standard Input in the following format:

H W
s_{1, 1} s_{1, 2} s_{1, 3} ... s_{1, W}
s_{2, 1} s_{2, 2} s_{2, 3} ... s_{2, W}
  :   :
s_{H, 1} s_{H, 2} s_{H, 3} ... s_{H, W}

Output

If square1001 can achieve his objective, print Yes; if he cannot, print No.

Sample Input 1

3 3
.#.
###
.#.

Sample Output 1

Yes

One possible way to achieve the objective is shown in the figure below. Here, the squares being painted are marked by stars.

Sample Input 2

5 5
#.#.#
.#.#.
#.#.#
.#.#.
#.#.#

Sample Output 2

No

square1001 cannot achieve his objective here.

Sample Input 3

11 11
...#####...
.##.....##.
#..##.##..#
#..##.##..#
#.........#
#...###...#
.#########.
.#.#.#.#.#.
##.#.#.#.##
..##.#.##..
.##..#..##.

Sample Output 3

Yes



Sample input:
3 3
.#.
###
.#.


Sample output:
Yes

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
paint = [list(input()) for _ in range(h)]
ans = 'Yes'
for i in range(h):
    for j in range(w):
        if paint[i][j] == '#':
            if i > 0:
                if paint[i - 1][j] == '#':
                    continue
            if i < h - 1:
                if paint[i + 1][j] == '#':
                    continue
            if j > 0:
                if paint[i][j - 1] == '#':
                    continue
            if j < w - 1:
                if paint[i][j + 1] == '#':
                    continue
            ans = 'No'
            break
print(ans)

Submission status: Accepted

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

s = [input() for _ in range(H)]

for h in range(H):
    for w in range(W):
        if s[h][w] == "#":
            if h > 0 and s[h-1][w] == "#":
                continue
            elif w < W-1 and s[h][w+1] == "#":
                continue
            elif h < H-1 and s[h+1][w] == "#":
                continue
            elif w > 0 and s[h][w-1] == "#":
                continue
            else:
                print("No")
                exit()
print("Yes")

Submission status: Accepted

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

ans = True
for i in range(H):
    for j in range(W):
        if s[i][j] == '.': continue
        #
        ans_tmp = False
        if i > 0 and s[i - 1][j] == "#": ans_tmp = True
        if j > 0 and s[i][j - 1] == "#": ans_tmp = True
        if i < H - 1 and s[i + 1][j] == "#": ans_tmp = True
        if j < W - 1 and s[i][j + 1] == "#": ans_tmp = True
        #
        ans = ans & ans_tmp

if ans:
    print('Yes')
else:
    print('No')

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
H, W = map(int, input().split())
S = [list(input())[: -1] for _ in range(H)]
d = [-1, 0, 1, 0]
for i in range(H):
  for j in range(W):
    if S[i][j] == ".": continue
    t = 0
    for k in range(4):
      y = i + d[k]
      x = j + d[-1 - k]
      if y in range(H) and (x in range(W)):
        t += S[y][x] == "#"
    if t: continue
    print("No")
    exit(0)
print("Yes")

Submission status: Accepted

Solution code:
h,w = map(int,input().split())
s = [input() for _ in range(h)]
dx = [1,0,-1,0]
dy = [0,1,0,-1]
for i in range(h):
    for j in range(w):
        if s[i][j]=='#':
            flag = False
            for k in range(4):
                if 0<=j+dx[k]<w and 0<=i+dy[k]<h:
                    if s[i+dy[k]][j+dx[k]]=='#':
                        flag = True
            if not flag:
                print('No')
                exit()
print('Yes')

Submission status: Accepted

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

for i in range(h):
    for j in range(w):
        if s[i][j] == '#':
            flag = False
            for di, dj in (-1, 0), (1, 0), (0, 1), (0, -1):
                ni, nj = i+di, j+dj
                if 0 <= ni < h and 0<= nj < w:
                    if s[ni][nj] == '#':
                        flag = True
            if not flag:
                print('No')
                exit()
else:
    print('Yes')

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]=='.': continue
        if 0<i and S[i-1][j]=='#': continue
        if i<H-1 and S[i+1][j]=='#': continue
        if 0<j and S[i][j-1]=='#': continue
        if j<W-1 and S[i][j+1]=='#': continue
        print('No')
        exit()
print('Yes')

Submission status: Accepted

Solution code:
def main():
    h, w = map(int, input().split())
    s = [list(input()) for _ in range(h)]
    delta = [[0, 1], [1, 0], [0, -1], [-1, 0]]
    black_count = 0
    for i in range(h):
        for j in range(w):
            if s[i][j] == "#":
                black_count += 1
                tmp = 0
                for dy, dx in delta:
                    new_y = dy + i
                    new_x = dx + j
                    if 0 <= new_y < h and 0 <= new_x < w:
                        if s[new_y][new_x] == "#":
                            tmp += 1
                if tmp > 0:
                    black_count -= 1
    print("Yes" if black_count == 0 else "No")


if __name__ == '__main__':
    main()

Submission status: Accepted

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

dxy = [(0,1),(1,0),(0,-1),(-1,0)]
for y in range(H):
    for x in range(W):
        if S[y][x]=='.': continue
        for dx,dy in dxy:
            nx,ny = x+dx,y+dy
            if not 0 <= nx < W: continue
            if not 0 <= ny < H: continue
            if S[ny][nx]=='#':
                break
        else:
            print('No')
            exit()
print('Yes')

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

H, W = MAP()

S = [input() for _ in range(H)]

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

for i in range(H):
	for j in range(W):
		if S[i][j] == "#":
			for k in range(4):
				y = i+dy[k]
				x = j+dx[k]
				if 0 <= y <= H-1 and 0 <= x <= W-1 and S[y][x] == "#":
					break
			else:
				print("No")
				exit()
print("Yes")

Submission status: Accepted

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

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

flag = 0
for i in range(H):
    for j in range(W):
        if s[i][j] == ".":
            pass
        else:
            if i > 0 and s[i-1][j] == "#":
                pass
            elif i < H-1 and s[i+1][j] == "#":
                pass
            elif j > 0 and s[i][j-1] == "#":
                pass
            elif j < W-1 and s[i][j+1] == "#":
                pass
            else:
                flag = 1

if flag != 1:
    print("Yes")
else:
    print("No")

Submission status: Accepted

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

for h in range(1, H+1):
    for w in range(1, W+1):
        if board[h][w] == "#" and board[h-1][w]=="." and board[h+1][w]=="." and board[h][w-1]=="." and board[h][w+1]==".":
            print("No")
            exit()
print("Yes")

Submission status: Accepted

Solution code:
if __name__ == '__main__':
    h, w = map(int, input().split())
    field = [list(input()) for i in range(h)]
    d = [(1, 0), (0, 1), (-1, 0), (0, -1)]
    for y in range(h):
        for x in range(w):
            flag = False
            if field[y][x] == "#":
                for dx, dy in d:
                    if 0 <= x + dx < w and 0 <= y + dy < h:
                        if field[y + dy][x + dx] == "#":
                            flag |= True
                if not flag:
                    print("No")
                    exit(0)
    print("Yes")

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
grid = ['.'*(W+2)]
for _ in range(H):
    grid.append('.'+input()+'.')
grid.append('.'*(W+2))
for i in range(1,H):
    for k in range(1,W):
        if grid[i][k] == '.':
            continue
        if grid[i-1][k] == '.' and grid[i+1][k] == '.' and grid[i][k-1] == '.' and grid[i][k+1] == '.':
            print('No')
            exit()
print('Yes')

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
a=input().split()
x=int(a[0])
y=int(a[1])
z=[]
c=[]
d=[[1,0],[0,-1],[-1,0],[0,1]]
ans=1
for i in range(x):
    a_list=[]
    for j in range(y):
        a_list.append(0)
    z.append(a_list)
for i in range(x):
    b=list(input())
    c.append(b)

for i in range(x):
    for j in range(y):
        if c[i][j]=="#":
            s=i
            t=j
            count=0
            for k in range(4):
                s=i+d[k][0]
                t=j+d[k][1]
                
                if (s>=0 and s<x) and (t>=0 and t<y):
                    
                    if c[s][t]=="#":
                        count+=1
                     
            if count==0:
                ans=0
                
if ans==1:
    print("Yes")
else:
    print("No")

Submission status: Accepted

Solution code:
h,w = map(int,input().split())
lines = []
for i in range(h):
  line = "." + input() + "."
  lines.append(line)
ans = "Yes"
ss = "." * (w+2)
lines.append(ss)
lines.insert(0,ss)
for j in range(1,h+1):
  for l in range(1,w+1):
    if lines[j][l] == "#" and lines[j-1][l] == "." and lines[j+1][l] == "." and lines[j][l-1] == "." and lines[j][l+1] == ".":
      ans = "No"
print(ans)

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
S = [input() for _ in range(H)]
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
for y in range(H):
    for x in range(W):
        if S[y][x] != '#':
            continue

        for i in range(4):
            if y + dy[i] < 0 or H <= y+dy[i] or x + dx[i] < 0 or W <= x+dx[i]:
                continue
            if S[y + dy[i]][x + dx[i]] == '#':
                break
        else:
            print('No')
            exit()

print('Yes')

Submission status: Accepted

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

mat=[]
mat.append([True]*(W+2))
for i in range(H):
  array=[True]+[x=="#" for x in input()]+[True]
  mat.append(array)
mat.append([True]*(W+2))
#print(mat)

for i in range(1,H+1):
  for j in range(1,W+1):
    if mat[i][j]:
      if not (mat[i-1][j] or mat[i+1][j] or mat[i][j-1] or mat[i][j+1]):
        print("No")
        sys.exit(0)
else:
  print("Yes")

Submission status: Accepted

Solution code:
h,w = map(int,input().split())
s = [input() for i in range(h)]
grid = [[0 for i in range(w+2)] for j in range(h+2)]
for i in range(h):
    for j in range(w):
        if s[i][j] == '#':
            grid[i+1][j+1] = 1
for i in range(1,h+1):
    for j in range(1,w+1):
        if grid[i][j] == 1:
            if grid[i-1][j]+grid[i+1][j]+grid[i][j-1]+grid[i][j+1] == 0:
                print('No')
                exit()
print('Yes')

Submission status: Accepted

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

S = []
for _ in range(H):
    tmp = list(input())
    S.append(tmp)

for h in range(H):
    for w in range(W):
        if S[h][w] == '#':
            # 上
            if h > 0 and S[h-1][w] == '#':
                continue
            # 下
            elif h < H-1 and S[h+1][w] == '#':
                continue
            # 左
            elif w > 0 and S[h][w-1] == '#':
                continue
            # 右
            elif w < W-1 and S[h][w+1] == '#':
                continue
            print('No')
            exit(0)

print('Yes')

Submission status: Accepted

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

# print(mass)
flag = 0
for i in range(H):
    for j in range(W):
        if mass[i][j] == ".":
            continue
        if 0 <= i-1 < H and mass[i-1][j] == '#':
            continue
        elif 0 <= i+1 < H and mass[i+1][j] == '#':
            continue
        elif 0 <= j-1 < H and mass[i][j-1] == '#':
            continue
        elif 0 <= j+1 < H and mass[i][j+1] == '#':
            continue
        else:
            # print(i, j)
            flag = 1
            break
if flag:
    print("No")
else:
    print("Yes")

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10000)
def resolve():
    H, W = list(map(int, input().split(" ")))
    S = ["."*(W+2)]
    S.extend(["."+input()+"." for i in range(H)])
    S.extend(["."*(W+2)])
    
    for i in range(H+2):
        for j in range(W+2):
            if S[i][j] == "#":
                if not (S[i-1][j] == "#" or S[i+1][j] == "#" or S[i][j-1] == "#" or S[i][j+1] == "#"):
                    print("No")
                    return
    print("Yes")
    
if '__main__' == __name__:
    resolve()

Submission status: Accepted

Solution code:
from collections import deque
h,w=map(int,input().split())
s=[deque(input())for _ in range(h)]
for i in range(h):
  s[i].append('.')
  s[i].appendleft('.')
  s[i]=tuple(s[i])
s=deque(s)
s.append(['.']*(w+2))
s.appendleft(['.']*(w+2))
s=tuple(s)
for i in range(1,h+1):
  for j in range(1,w+1):
    l=[s[i-1][j],s[i][j+1],s[i+1][j],s[i][j-1]]
    if s[i][j]=='#' and all(k=='.' for k in l):
      print('No')
      exit()
print('Yes')

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
s=[list(input()) for _ in range(h)]
#print(s)
for i in range(h):
    for j in range(w):
        #print(i,j)
        if s[i][j]=="#":
            if i!=0:
                if s[i-1][j]=="#":
                    continue
            if i!=h-1:
                if s[i+1][j]=="#":
                    continue
            if j!=0:
                if s[i][j-1]=="#":
                    continue
            if j!=w-1:
                if s[i][j+1]=="#":
                    continue
            print("No")
            exit()
print("Yes")

Submission status: Accepted

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

dw = [1, 0, -1, 0]
dh = [0, 1, 0, -1]

for i in range(H):
    for j in range(W):
        if cvs[i][j] == '#':
            ok = False
            for k in range(4):
                if 0<=i+dh[k]<=H-1 and 0<=j+dw[k]<=W-1:
                    if cvs[i+dh[k]][j+dw[k]] == '#':
                        ok = True
                        break
            if ok == False:
                print('No')
                exit()
print('Yes')

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
s = []
dh = [-1, 1, 0, 0]
dw = [0, 0, -1, 1]
ans = "Yes"

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

for i in range(h):
    for j in range(w):
        ok = False
        if s[i][j] == '#':
            for k in range(len(dh)):
                if 0<=i+dh[k]<=h-1 and 0<=j+dw[k]<=w-1:
                    if s[i+dh[k]][j+dw[k]] == '#':
                        ok = True
                        break
            if not(ok):
                ans = "No"
            

print(ans)

Submission status: Accepted

Solution code:
def main():
    h,w = map(int, input().split())
    S = ['.'*(w+2)]
    for i in range(h):
        S.append('.'+input()+'.')
    S.append('.'*(w+2))
    for hi in range(1,h+1):
        for wi in range(1,w+1):
            if S[hi][wi]=='#':
                if '#' in [S[hi][wi-1],S[hi][wi+1],S[hi-1][wi],S[hi+1][wi]]:
                    continue
                else:
                    print('No')
                    return
    print('Yes')


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from sys import stdin
def main():
    input = stdin.readline
    h, w = map(int, input().split())

    def banpei_grid(H,W):
       S = ["#" * (W + 2)]
       for i in range(H):
           S += ["#" + input()+ "#"]
       S += ["#" * (W + 2)]
       return S
       
    s = banpei_grid(h, w)

    from itertools import product
    for i, j in product(range(h), range(w)):
        ss = s[i][j]
        if ss == "#":
            if s[i+1][j] == "#":
                continue
            elif s[i][j+1] == "#":
                continue
            elif s[i-1][j] == "#":
                continue
            elif s[i][j-1] == "#":
                continue

            else:
                print("No")
                exit()
    else:
        print("Yes")


if __name__ == '__main__':
    main()

Submission status: Accepted

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

ban = [[False] * W for _ in range(H)]
for i in range(H):
    for j in range(W):
        if s[i][j] == ".":
            ban[i][j] = True
def solve(i, j):
    for dy, dx in [(-1, 0), (1, 0), (0, 1), (0, -1)]:
        if 0 <= i + dy < H and 0<= j + dx < W:
            if s[i+dy][j+dx] == "#":
                ban[i][j] = True
                ban[i+dy][j+dx] = True
    return

for i in range(H):
    for j in range(W):
        if s[i][j] == "#":
            solve(i, j)

for h in range(H):
    if not all(ban[h][i] for i in range(W)):
        print("No")
        break
else:
    print("Yes")

Submission status: Accepted

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

for i in range(1,h-1):
    for j in range(1,w-1):
        if s[i][j]=="#" and s[i-1][j]==s[i+1][j]==s[i][j-1]==s[i][j+1]==".":
            print("No") 
            exit()
print("Yes")

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
s = [[c for c in str(input())] for i in range(h)]
#print(s)
cando = True
for i in range(h):
  for j in range(w):
    if s[i][j] == '.': continue
    adj = False
    if i > 0 and s[i-1][j] == '#': adj = True
    if i < h-1 and s[i+1][j] == '#': adj = True
    if j > 0 and s[i][j-1] == '#': adj = True
    if j < w-1 and s[i][j+1] == '#': adj = True
    if not adj:
      cando = False
      break
  if not cando: break
if cando: print('Yes')
else: print('No')

Submission status: Accepted

Solution code:
from itertools import product
from collections import deque
import numpy as np
inputs = open(0).readlines()
class Grid():
    def __init__(self, grid, w=0, h=0, function=lambda x: x):
        self.w = w = w if w else len(grid[0])
        self.h = h = h if h else len(grid)
        dtype = type(function(grid[0][0]))
        self.grid = np.empty((h, w), dtype=dtype)
        for i, row in zip(range(h), grid):
            for j, val in zip(range(w), row):
                self.grid[i][j] = function(val)
    
    def is_valid_x(self, x):
        return 0 <= x < self.w
    def is_valid_y(self, y):
        return 0 <= y < self.h
    def is_valid_xy(self, x, y):
        return self.is_valid_x(x) and self.is_valid_y(y) 
    
    def __iter__(self):
        return iter(self.grid)
    def __repr__(self):
        return '\n'.join([' '.join(map(str, row)) for row in self.grid])
    def __getitem__(self, x):
        return self.grid[x]
    def __setitem__(self, x, val):
        self.grid[x] = val

h, w = map(int, inputs[0].split())
grid = Grid(inputs[1:], function=lambda x: int(x == '#'))

def dfs(root):
    count = 1
    x, y = root
    grid[y, x] = 0
    stack = [root]
    while stack:
        x, y = stack.pop()
        grid[y, x] = 0
        for dx, dy in zip([1, 0, -1, 0], [0, 1, 0, -1]):
            if grid.is_valid_xy(x+dx, y+dy) and grid[y+dy, x+dx]:
                stack.append((x+dx, y+dy))
                count += 1
    return count
    
ans = 'Yes'
for i, j in product(range(h), range(w)):
    if grid[i, j]:
        if dfs((j, i)) == 1:
            ans = 'No'
            break
print(ans)

Submission status: Accepted

Solution code:
from itertools import product
from collections import deque
import numpy as np
inputs = open(0).readlines()
class Grid():
    def __init__(self, grid, w=0, h=0, function=lambda x: x):
        self.w = w = w if w else len(grid[0])
        self.h = h = h if h else len(grid)
        dtype = type(function(grid[0][0]))
        self.grid = np.empty((h, w), dtype=dtype)
        for i, row in zip(range(h), grid):
            for j, val in zip(range(w), row):
                self.grid[i][j] = function(val)
    
    def is_valid_x(self, x):
        return 0 <= x < self.w
    def is_valid_y(self, y):
        return 0 <= y < self.h
    def is_valid_xy(self, x, y):
        return self.is_valid_x(x) and self.is_valid_y(y) 
    
    def __iter__(self):
        return iter(self.grid)
    def __repr__(self):
        return '\n'.join([' '.join(map(str, row)) for row in self.grid])
    def __getitem__(self, x):
        return self.grid[x]
    def __setitem__(self, x, val):
        self.grid[x] = val

h, w = map(int, inputs[0].split())
grid = Grid(inputs[1:], function=lambda x: int(x == '#'))

from collections import deque
def bfs(root):
    count = 1
    x, y = root
    grid[y, x] = 0
    queue = deque([root])
    while queue:
        x, y = queue.popleft()
        for dx, dy in zip([1, 0, -1, 0], [0, 1, 0, -1]):
            if grid.is_valid_xy(x+dx, y+dy) and grid[y+dy, x+dx]:
                queue.append((x+dx, y+dy))
                grid[y+dy, x+dx] = 0
                count += 1
    return count
    
ans = 'Yes'
for i, j in product(range(h), range(w)):
    if grid[i, j]:
        if bfs((j, i)) == 1:
            ans = 'No'
            break
print(ans)

Submission status: Accepted

Solution code:
from itertools import product
from collections import deque
import numpy as np
inputs = open(0).readlines()
class Grid():
    def __init__(self, grid, w=0, h=0, function=lambda x: x):
        self.w = w = w if w else len(grid[0])
        self.h = h = h if h else len(grid)
        dtype = type(function(grid[0][0]))
        self.grid = np.empty((h, w), dtype=dtype)
        for i, row in zip(range(h), grid):
            for j, val in zip(range(w), row):
                self.grid[i][j] = function(val)
    
    def is_valid_x(self, x):
        return 0 <= x < self.w
    def is_valid_y(self, y):
        return 0 <= y < self.h
    def is_valid_xy(self, x, y):
        return self.is_valid_x(x) and self.is_valid_y(y) 
    
    def __iter__(self):
        return iter(self.grid)
    def __repr__(self):
        return '\n'.join([' '.join(map(str, row)) for row in self.grid])
    def __getitem__(self, x):
        return self.grid[x]
    def __setitem__(self, x, val):
        self.grid[x] = val

h, w = map(int, inputs[0].split())
grid = Grid(inputs[1:], function=lambda x: int(x == '#'))

def dfs(root):
    count = 1
    stack = [root]
    while stack:
        x, y = stack.pop()
        for dx, dy in zip([1, 0, -1, 0], [0, 1, 0, -1]):
            if grid.is_valid_xy(x+dx, y+dy) and grid[y+dy, x+dx]:
                stack.append((x+dx, y+dy))
                grid[y+dy, x+dx] = 0
                count += 1
    return count
    
ans = 'Yes'
for i, j in product(range(h), range(w)):
    if grid[i, j]:
        if dfs((j, i)) == 1:
            ans = 'No'
            break
print(ans)

Submission status: Accepted

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

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

for i in range(H):
  for j in range(W):
    if s[i][j] == '#':
      count = 0
      for k in range(4):
        x = j + dx[k]
        y = i + dy[k]
        if 0 <= x < W and 0 <= y < H:
          if s[y][x] == '#':
            count += 1
       
      if count == 0:
        print('No')
        exit()
print('Yes')

Submission status: Accepted

Solution code:
def solve():
    H, W = map(int, input().split())
    S = [list(input()) for i in range(H)]
    org = [[0] * W for i in range(H)]
    # 縦ループ
    for i in range(H):
        #　横ループ
        for j in range(W):
            org[i][j] = S[i][j]
            if S[i][j] == '#':
                if canPaint(i, j, S, H, W) == True:
                    continue
                else:
                    return False
            else:
                continue
    return True


def canPaint(i, j, S, H, W):
    for x in range(-1, 2):
        for y in range(-1, 2):
            # その場と斜め以外の場合
            if (x == 0 or y == 0) and (x != 0 or y != 0):
                dx = x + j
                dy = y + i
                # 移動不可能
                if dx < 0 or dx > W - 1 or dy < 0 or dy > H - 1:
                    continue
                else:
                    if S[dy][dx] == '#':
                        return True
    return False
def main():
    if solve() == True:
        print('Yes')
    else:
        print('No')

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
h,w = map(int,input().split())
grid = []
grid.append(["."]*(w+2))
for i in range(h):
    a = list(input())
    a.insert(0,".")
    a.append(".")
    grid.append(a)
grid.append(["."]*(w+2))
for i in range(1, h+1):
    for j in range(1, w+1):
        nei = [grid[i+1][j], grid[i-1][j], grid[i][j-1], grid[i][j+1]]
        if grid[i][j] == "#" and "#" not in nei:
            print("No")
            exit()
print("Yes")

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
s = ["."*(W+2)]
for i in range(H):
    temp = "."
    temp += input()
    temp += "."
    s.append(temp)
s.append("."*(W+2))
flag = True
for i in range(1, H+1):
    for j in range(1, W+1):
        if s[i][j] == "#" and s[i-1][j] == "." and s[i+1][j] == "." and s[i][j-1] == "." and s[i][j+1] == ".":
            flag = False
            break
    if not flag:
        break
if flag:
    result = "Yes"
else:
    result = "No"
print(result)

Submission status: Accepted

Solution code:
import numpy as np
h, w = list(map(int, input().split()))
s = np.array([list(input()) for i in range(h)])

infer = []
for i in range(h):
  for j in range(w):
    if s[i][j] == "#":
      pts = set([
        (max(0, i-1), j), 
        (i, max(0, j-1)), 
        (min(h-1, i+1), j), 
        (i, min(w-1, j+1))
      ])
      check = np.array([ s[ix][iy] for ix, iy in list(pts - set([(i, j)])) ])
      infer.append((check == "#").sum())

print("No" if 0 in infer else "Yes")

Submission status: Accepted

Solution code:
from itertools import product
from collections import deque
import numpy as np
inputs = open(0).readlines()
class Grid():
    def __init__(self, grid, w=0, h=0, function=lambda x: x):
        self.w = w = w if w else len(grid[0])
        self.h = h = h if h else len(grid)
        dtype = type(function(grid[0][0]))
        self.grid = np.empty((h, w), dtype=dtype)
        for i, rows in zip(range(h), grid):
            for j, val in zip(range(w), rows):
                self.grid[i][j] = function(val)
    
    def is_valid_x(self, x):
        return 0 <= x < self.w
    def is_valid_y(self, y):
        return 0 <= y < self.h
    def is_valid_xy(self, x, y):
        return self.is_valid_x(x) and self.is_valid_y(y) 
    
    def __iter__(self):
        return iter(self.grid)
    def __repr__(self):
        return '\n'.join([' '.join(map(str, rows)) for rows in self.grid])
    def __getitem__(self, x):
        return self.grid[x]
    def __setitem__(self, x, val):
        self.grid[x] = val

h, w = map(int, inputs[0].split())
grid = Grid(inputs[1:], function=lambda x: int(x == '#'))

def dfs(root):
    count = 1
    stack = [root]
    while stack:
        x, y = stack.pop()
        grid[y, x] = 0
        for dx, dy in zip([1, 0, -1, 0], [0, 1, 0, -1]):
            if grid.is_valid_xy(x+dx, y+dy) and grid[y+dy, x+dx]:
                stack.append((x+dx, y+dy))
                count += 1
    return count

def bfs(root):
    count = 1
    queue = deque([root])
    while queue:
        x, y = queue.popleft()
        grid[y, x] = 0
        for dx, dy in zip([1, 0, -1, 0], [0, 1, 0, -1]):
            if grid.is_valid_xy(x+dx, y+dy) and grid[y+dy, x+dx]:
                queue.append((x+dx, y+dy))
                count += 1
    return count  

ans = 'Yes'
for i, j in product(range(h), range(w)):
    if grid[i, j]:
        if dfs((j, i)) == 1:
            ans = 'No'
            break
print(ans)

Submission status: Accepted

Solution code:
from itertools import product
import numpy as np
inputs = open(0).readlines()

class Grid():
    def __init__(self, grid, w=0, h=0, function=lambda x: x):
        self.w = w = w if w else len(grid[0])
        self.h = h = h if h else len(grid)
        dtype = type(function(grid[0][0]))
        self.grid = np.empty((h, w), dtype=dtype)
        for i, rows in zip(range(h), grid):
            for j, val in zip(range(w), rows):
                self.grid[i][j] = function(val)
    
    def is_valid_x(self, x):
        return 0 <= x < self.w
    def is_valid_y(self, y):
        return 0 <= y < self.h
    def is_valid_xy(self, x, y):
        return self.is_valid_x(x) and self.is_valid_y(y) 
    
    def __iter__(self):
        return iter(self.grid)
    def __repr__(self):
        return '\n'.join([' '.join(map(str, rows)) for rows in self.grid])

h, w = map(int, inputs[0].split())
grid = Grid(inputs[1:])

def dfs(root):
    count = 1
    stack = [root]
    while stack:
        x, y = stack.pop()
        grid.grid[y, x] = '.'
        for dx, dy in zip([1, 0, -1, 0], [0, 1, 0, -1]):
            if grid.is_valid_xy(x+dx, y+dy) and grid.grid[y+dy, x+dx] == '#':
                stack.append((x+dx, y+dy))
                count += 1
    return count

ans = 'Yes'
for i, j in product(range(h), range(w)):
    if grid.grid[i, j] == '#':
        if dfs((j, i)) == 1:
            ans = 'No'
            break
print(ans)

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
S = ['.'*(W+2)] + ['.' + input() + '.' for _ in range(H)] + ['.'*(W+2)]
flg = False
for i in range(1, H+1):
  for j in range(1, W+1):
    if S[i][j] == '#':
      cnt = 0
      if S[i][j-1] == '.':
        cnt += 1
      if S[i][j+1] == '.':
        cnt += 1
      if S[i-1][j] == '.':
        cnt += 1
      if S[i+1][j] == '.':
        cnt += 1
      flg = (cnt == 4)
      if flg:
        break
  if flg:
    break
if flg:
  print("No")
else:
  print("Yes")