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())
s = [list(input()) for _ in range(h)]

for y in range(h):
    for x in range(w):
        if s[y][x] == ".":
            continue
        if 0 < x < w-1:
            if 0 < y < h-1:
                if s[y][x-1] == "." and s[y][x+1] == "." and s[y-1][x] == "." and s[y+1][x] == ".":
                    print("No")
                    exit()
            elif y == 0:
                if s[y][x-1] == "." and s[y][x+1] == "." and s[y+1][x] == ".":
                    print("No")
                    exit()
            else:
                if s[y][x-1] == "." and s[y][x+1] == "." and s[y-1][x] == ".":
                    print("No")
                    exit()
        elif x == 0:
            if 0 < y < h-1:
                if s[y][x+1] == "." and s[y-1][x] == "." and s[y+1][x] == ".":
                    print("No")
                    exit()
            elif y == 0:
                if s[y][x+1] == "." and s[y+1][x] == ".":
                    print("No")
                    exit()
            else:
                if s[y][x+1] == "." and s[y-1][x] == ".":
                    print("No")
                    exit()
        else:
            if 0 < y < h-1:
                if s[y][x-1] == "." and s[y-1][x] == "." and s[y+1][x] == ".":
                    print("No")
                    exit()
            elif y == 0:
                if s[y][x-1] == "." and s[y+1][x] == ".":
                    print("No")
                    exit()
            else:
                if s[y][x-1] == "." and s[y-1][x] == ".":
                    print("No")
                    exit()
print("Yes")

Submission status: Accepted

Solution code:
h,w=map(int,input().split()) 
l = [input() for _ in range(h)]
dx = [1,-1,0,0]
dy = [0,0,1,-1]
for i in range(h):
    for j in range(w):
        if l[i][j] =='#':
            cnt = 0
            for di in range(4):
                y = i+dx[di]
                x = j+dy[di]
                if x<0 or y<0 or x>w-1 or y>h-1:
                    continue
                else:
                    if l[y][x] =='#':
                        cnt +=1
            if cnt == 0:
                print('No')
                exit()

print('Yes')

Submission status: Accepted

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

Submission status: Accepted

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

mx = [0, 1, 0, -1]#yとの兼ね合いで片方は0にして上下左右判定
my = [1, 0, -1, 0]#xとの兼ね合いで片方は0にして上下左右判定
for i in range(h):
    for j in range(w):
        if table[i][j] == "#":
            for k in range(4):
                tx = j + mx[k]#左右判定
                ty = i + my[k]#上下判定
                if 0 <= tx < w and 0 <= ty < h and table[ty][tx] == "#":#添え字に使えるか判定している
                    break
            else:#breakされなかった時実行される、上下左右に#がなかった時になる
                print("No")
                exit(0)
print("Yes")

Submission status: Accepted

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

mx = [0, 1, 0, -1]
my = [1, 0, -1, 0]
for i in range(h):
    for j in range(w):
        if table[i][j] == "#":
            for k in range(4):
                tx, ty = j + mx[k], i + my[k]
                if 0 <= tx < w and 0 <= ty < h and table[ty][tx] == "#":
                    break
            else:
                print("No")
                exit(0)
print("Yes")

Submission status: Accepted

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

for i in range(1,H-1):
    for j in range(1,W-1):
        if s[i][j]=='#' and s[i][j+1]==s[i+1][j]==s[i][j-1]==s[i-1][j]=='.':
                print('No')
                exit()
print(ans)

Submission status: Accepted

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

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

for i in range(H):
    for j in range(W):
        if sq[i][j]=="#":
            temp=0
            if j!=0:
                if sq[i][j-1]=="#":
                    temp+=1
            if j!=W-1:
                if sq[i][j+1]=="#":
                    temp+=1
            if i!=0:
                if sq[i-1][j]=="#":
                    temp+=1
            if i!=H-1:
                if sq[i+1][j]=="#":
                    temp+=1
            if temp==0:
                print("No")
                exit()

print("Yes")

Submission status: Accepted

Solution code:
#上下左右に#が全て隣接しているならOK

N, M = map(int, input().split())
#print(N)
c = 0
l = []
for i in range(N):
  l.append(list(input()))
  
#print(l)
N -= 1
M -= 1

for i in range(N):
  for j in range(M):
    if l[i][j] == ".":
      pass
    else:
      if i-1>=0 and i+1<=N and j-1>=0 and j+1<=M and l[i-1][j] == "." and l[i+1][j] == "." and l[i][j-1] == "." and l[i][j+1] == ".":
        c+=1
      if i==0 and j-1>=0 and j+1<=M and l[i+1][j] == "." and l[i][j-1] == "." and l[i][j+1] == ".":
        c+=1
      if i-1>=0 and i+1<=N and j==0 and l[i-1][j] == "." and l[i+1][j] == "." and l[i][j+1] == ".":
        c+=1
      if i==N and j-1>=0 and j+1<=M and l[i-1][j] == "." and l[i][j-1] == "." and l[i][j+1] == ".":
        c+=1
      if i-1>=0 and i+1<=N and j-1>=0 and j==M and l[i-1][j] == "." and l[i+1][j] == "." and l[i][j-1] == ".":
        c+=1
      if i==0 and j==0 and l[i+1][j] == "." and l[i][j+1] == ".":
        c+=1
      if i==0 and j==M and l[i+1][j] == "." and l[i][j-1] == ".":
        c+=1
      if i==N and j==0 and l[i-1][j] == "." and l[i][j+1] == ".":
        c+=1
      if i==N and j==M and l[i-1][j] == "." and l[i][j-1] == ".":
        c+=1

if c == 0:
  print("Yes")
else:
  print("No")

Submission status: Accepted

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

for i in range(len(x)):
    x[i].insert(0, ".")
    x[i].append(".")
x.insert(0, ["."]*(W+2))
x.append(["."]*(W+2))

for i in range(1, H+1):
    for j in range(1, W+1):
        if x[i][j] == "#":
            if x[i][j-1] == x[i][j+1] == x[i-1][j] == x[i+1][j] == ".":
                print("No")
                exit()
print("Yes")

Submission status: Accepted

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

flug = True
for i in range(H):
    for j in range(W):
        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] == '#'):
                flug = False
if flug:
    print("Yes")
else:
    print("No")

Submission status: Accepted

Solution code:
import re
import sys
import math
import itertools
import bisect
from copy import copy
from collections import deque,Counter
from decimal import Decimal
import functools
def v(): return input()
def k(): return int(input())
def S(): return input().split()
def I(): return map(int,input().split())
def X(): return list(input())
def L(): return list(input().split())
def l(): return list(map(int,input().split()))
def lcm(a,b): return a*b//math.gcd(a,b)
sys.setrecursionlimit(10 ** 6)
mod = 10**9+7
cnt = 0
ans = 0
inf = float("inf")
al = "abcdefghijklmnopqrstuvwxyz"
AL = al.upper()

H, W = I()

pad_s = ['.'*(W+2)]
for h in range(H):
  pad_s.append('.' + input() + '.')
pad_s.append('.'*(W+2))

for i,ss in enumerate(pad_s):
  for j,s in enumerate(ss):
    if s == '#'\
      and pad_s[i][j+1] == '.'\
      and pad_s[i][j-1] == '.'\
      and pad_s[i+1][j] == '.'\
      and pad_s[i-1][j] == '.':
      print('No')
      exit()

print('Yes')

Submission status: Accepted

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

for h in range(H):
    for w in range(W):
        if S[h][w] in ['.', 'B']: continue
        
        ary = [[0,1], [0,-1], [1,0], [-1,0]]
        flag = False
        for x, y in ary:
            xd = h+x
            yd = w+y
            if xd < 0 or xd >= H or yd < 0 or yd >=W: continue
            if S[xd][yd] in ['B', '#']:
                S[h][w] = 'B'
                S[xd][yd] = 'B'
                flag = True
        
        if not flag:
            print('No') 
            exit()

print('Yes')

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys
import copy
import math
import itertools
import numpy as np

H,W = [int(c) for c in input().split()]
s = [list(input()) for c in range(H)]
a = [[1 for c in range(W)] for d in range(H)]
b = [[0 for c in range(W)] for d in range(H)]

for i in range(H):
    for j in range(W):
        if s[i][j]=="#":
            if i-1 >= 0:
                if s[i-1][j] == "#":
                    a[i][j]=0
            if j-1 >= 0:
                if s[i][j-1] == "#":
                    a[i][j]=0
            if j+1 < W:
                if s[i][j+1] == "#":
                    a[i][j]=0
            if i+1 < H:
                if s[i+1][j] == "#":
                    a[i][j]=0
        else:
            a[i][j]=0
        if a[i][j] == 1:
            print("No")
            sys.exit(0)

print("Yes")

Submission status: Accepted

Solution code:
import re
import copy

def accept_input():
    H, W = map(int, input().split())
    S = []
    for _ in range(H):
        S.append(input())
    return H,W,S

def process(s):
    if s == "#":
        return 1
    else:
        return 0
H,W,S = accept_input()
arr1 = [(-1,-1),(-1,0),(-1,1),(1,-1),(1,0),(1,1),(0,1),(0,-1)]
arr = [(-1,0),(1,0),(0,1),(0,-1)]
new_S = copy.deepcopy(S)
g = 0
b = 0
for i in range(H):
    for j in range(W):
        if new_S[i][j] == "#":
            bl = 0
            for idou in arr:
                if i+idou[0] == -1 or i+idou[0] == H:
                    continue
                elif j+idou[1] == -1 or j+idou[1] == W:
                    continue
                else:
                    if new_S[i+idou[0]][j+idou[1]] == "#":
                        bl = 1
            if bl != 1:
                b = 1
                break
    if b == 1:
        break
if b == 1:
    print("No")
else:
    print("Yes")

Submission status: Accepted

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

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

for i in range(h):
    for j in range(w):
        if s[i][j] == '#':
            cnt = 0
            for p in range(4):
                if i + dh[p] < 0 or i + dh[p] >= h or j + dw[p] < 0 or j + dw[p] >= w:
                    continue
                else:
                    if s[i + dh[p]][j + dw[p]] == '#':
                        cnt += 1
            if cnt == 0:
                flag = 1
                break
        if flag == 1:
            break
    if flag == 1:
        print('No')
        break
else:
    print('Yes')

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
s=[input() for _ in range(H)]
cells=[(i,j) for i in range(H) for j in range(W)]
di=[1,0,-1,0]
dj=[0,1,0,-1]

for i,j in cells:
    if s[i][j]=='.':
        continue
    flag=False
    for k in range(4):
        ni=i+di[k]
        nj=j+dj[k]
        if ni<0 or nj<0 or ni>=H or nj>=W:
            continue
        if s[ni][nj]=='#':
            flag=True
    if not flag:
        print("No")
        break
else:
    print("Yes")

Submission status: Accepted

Solution code:
import sys
# sys.setrecursionlimit(100000)


def input():
    return sys.stdin.readline().strip()


def input_int():
    return int(input())


def input_int_list():
    return [int(i) for i in input().split()]


def main():
    h, w = input_int_list()
    grid = []
    grid.append(["."] * (w + 2))
    for _ in range(h):
        grid.append(["."] + list(input()) + ["."])
    grid.append(["."] * (w + 2))

    directions = ((1, 0), (0, 1), (-1, 0), (0, -1))

    for i in range(1, h + 1):
        for j in range(1 + w + 1):
            # "#"の周りに１つでも"#"がつながっていないか調べる
            if grid[i][j] == "#":
                cnt = 0
                for x, y in directions:
                    if grid[i + x][j + y] == "#":
                        cnt += 1
                if cnt == 0:
                    print("No")
                    return
    print("Yes")
    return


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from itertools import product


H, W = map(int, input().split())
s = [input() for _ in range(H)]
for i, j in product(range(H), range(W)):
    if s[i][j] == ".":
        continue
    is_ok = False
    for di, dj in (1, 0), (-1, 0), (0, 1), (0, -1):
        ni, nj = i + di, j + dj
        if not (0 <= ni < H and 0 <= nj < W):
            continue
        if s[ni][nj] == "#":
            is_ok = True
    if not is_ok:
        print("No")
        break
else:
    print("Yes")

Submission status: Accepted

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

for i in range(H):
    a=[i for i in input()]
    s.append(a)


for i in range(H):
    for j in range(W):
        if s[i][j]=='#':
            f=0
            for x,y in [(j,i+1),(j+1,i),(j,i-1),(j-1,i)]:
                if x<0 or x>W-1 or y<0 or y>H-1:
                    continue
                if s[y][x]=='#':
                    f=1
                    break
            if f==0:
                print('No')
                exit()

print('Yes')

Submission status: Accepted

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

for y in range(1, h + 1):
    for x in range(1, w + 1):
        if s[y][x] == '#' and all(s[y + dy][x + dx] == '.' for dy, dx in [(1, 0), (0, 1), (-1, 0), (0, -1)]):
            print('No')
            exit()
print('Yes')

Submission status: Accepted

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

for y in range(1, h + 1):
    for x in range(1, w + 1):
        if s[y][x] == '.':
            continue
        ok = False
        for dy, dx in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
            if s[y + dy][x + dx] == '#':
                ok = True
        if not ok:
            print('No')
            exit()
print('Yes')

Submission status: Accepted

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

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


print('Yes')

Submission status: Accepted

Solution code:
#from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from fractions import gcd
from itertools import combinations,permutations,accumulate, product # (string,3) 3回
#from collections import deque
from collections import deque,defaultdict,Counter
import decimal
import re
import math
import bisect
import heapq
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#
# my_round_int = lambda x:np.round((x*2 + 1)//2)
# 四捨五入g
#
# インデックス系
# int min_y = max(0, i - 2), max_y = min(h - 1, i + 2);
# int min_x = max(0, j - 2), max_x = min(w - 1, j + 2);
#
#
import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7
#mod = 9982443453
#mod = 998244353
from sys import stdin
readline = stdin.readline
def readInts():
  return list(map(int,readline().split()))
def readTuples():
    return tuple(map(int,readline().split()))
def I():
  return int(readline())
h,w = readInts()
maze = [input() for _ in range(h)]
dxy = [(-1,0),(1,0),(0,1),(0,-1)]
flag = True
for y in range(h):
    for x in range(w):
        if maze[y][x] == '#':
            ok = False
            for dy,dx in dxy:
                ny = y + dy
                nx = x + dx
                if not(0 <= ny < h and 0 <= nx < w):
                    continue
                if maze[ny][nx] == '#':
                    ok = True
                    break
            if ok:
                flag = True
            else:
                flag = False
                break
    if not flag:
        break
if flag:
    print('Yes')
else:
    print('No')

Submission status: Accepted

Solution code:
import sys

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

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

for i, row in enumerate(S):
    for j, s in enumerate(row):
        if s == ".":
            continue
        ok = False
        for k in range(4):
            nx = j + dx[k]
            ny = i + dy[k]
            if not(0 <= nx < W and 0 <= ny < H):
                continue
            if S[ny][nx] == "#":
                ok = True
        if ok is False:
            print("No")
            exit()

print("Yes")

Submission status: Accepted

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

for i in range(H):
    for j in range(W):
        if Map[i][j] == '#':
            for dy, dx in ((1, 0), (0, 1), (-1, 0), (0, -1)):
                ny = i + dy
                nx = j + dx
                if ny < 0 or ny >= H or nx < 0 or nx >= W:
                    continue
                if Map[ny][nx] == '#':
                    break
            else:
                print('No')
                exit()
print('Yes')

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
s = [list(input()) for _ in range(H)]
a = [[-1]*W for _ in range(H)]
for i in range(H):
  for j in range(W):
    if s[i][j] == ".":
      a[i][j] = 1
    dh = [-1,0,1,0]
    dw = [0,-1,0,1]
    for k in range(4):
      ii = i + dh[k]
      jj = j + dw[k]
      if 0 <= ii < H and 0 <= jj < W:
        if s[i][j] == "#" and s[ii][jj] == "#":
          a[i][j] = 1
          a[ii][jj] = 1
flag = True
for i in range(H):
  for j in range(W):
    if a[i][j] != 1:
      flag = False
      break
if flag:
  print("Yes")
else:
  print("No")

Submission status: Accepted

Solution code:
import sys


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


def LSH(h):
    return [input() for _ in range(h)]


H, W = LI()
masu = LSH(H)
for i in range(H):
    for j in range(W):
        ok = 0
        if masu[i][j] == ".":
            continue
        if j+1 < W:
            if masu[i][j+1] == "#":
                ok = 1
        if j-1 >= 0:
            if masu[i][j-1] == "#":
                ok = 1
        if i+1 < H:
            if masu[i+1][j] == "#":
                ok = 1
        if i-1 >= 0:
            if masu[i-1][j] == "#":
                ok = 1
        if ok == 0:
            print("No")
            sys.exit()
print("Yes")

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
S = [input().strip() for _ in range(H)]
flag = 0
for i in range(H):
    for j in range(W):
        if S[i][j]=="#":
            if j+1<W and S[i][j+1]=="#" or i-1>=0 and S[i-1][j]=="#" or j-1>=0 and S[i][j-1]=="#"\
            or i+1<H and S[i+1][j]=="#":
                continue
            else:
                flag = 1
                break
    if flag==1:break
if flag==0:
    print("Yes")
else:
    print("No")

Submission status: Accepted

Solution code:

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

for i in range(h):
    for j in range(w):
        if s[i][j] == '.':
            continue
        ok = False
        for dx, dy in [(1, 0), (0, 1), (0, -1), (-1, 0)]:
            nx = j + dx
            ny = i + dy
            if 0 <= nx < w and 0 <= ny < h and s[ny][nx] == '#':
                ok = True
        if not ok:
            print('No')
            exit()
print('Yes')

Submission status: Accepted

Solution code:
from sys import exit
h, w = map(int, input().split())
S = [input() for i in range(h)]
for i, T in enumerate(S):
    for j, t in enumerate(T):
        if t == "#":
            flag = 0
            if j > 0:
                if T[j - 1] == "#":
                    flag += 1
            if j < w - 1:
                if T[j + 1] == "#":
                    flag += 1
            if i > 0:
                if S[i - 1][j] == "#":
                    flag += 1
            if i < h - 1:
                if S[i + 1][j] == "#":
                    flag += 1
            if flag == 0:
                print("No")
                exit()
print("Yes")

Submission status: Accepted

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

for i in range(h):
    for j in range(w):
        if s[i][j] == "#":
            flag = False
            for i_new, j_new in [(i+1, j), (i-1, j), (i,j+1), (i,j-1)]:
                if i_new<0 or i_new>=h or j_new<0 or j_new>=w: continue
                if s[i_new][j_new] == "#":
                    flag = True
                    break
            if not flag:
                print("No")
                exit()
print("Yes")

Submission status: Accepted

Solution code:
# ===============================================================================================
# importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import *
from copy import *
from collections import deque
from collections import Counter as counter  # Counter(list)  return a dict with {key: count}
from itertools import combinations as comb  # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
# If the element is already present in the list,



# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect

# If the element is already present in the list,
# the right most position where element has to be inserted is returned

# ==============================================================================================
# fast I/O region

BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()


if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

# inp = lambda: sys.stdin.readline().rstrip("\r\n")

# ===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType


def iterative(f, stack=[]):
    def wrapped_func(*args, **kwargs):
        if stack: return f(*args, **kwargs)
        to = f(*args, **kwargs)
        while True:
            if type(to) is GeneratorType:
                stack.append(to)
                to = next(to)
                continue
            stack.pop()
            if not stack: break
            to = stack[-1].send(to)
        return to

    return wrapped_func


###### END ITERATE RECURSION ####

# ===============================================================================================
# some shortcuts

mod = 1000000007


def inp(): return sys.stdin.readline().rstrip("\r\n")  # for fast input

def integer(): return int(inp())


def out(var): sys.stdout.write(str(var))  # for fast output, always take string


def lis(): return list(map(int, inp().split()))


def stringlis(): return list(map(str, inp().split()))


def sep(): return map(int, inp().split())


def strsep(): return map(str, inp().split())


def zerolist(n): return [0] * n


def nextline(): out("\n")  # as stdout.write always print sring.


def testcase(t):
    for p in range(t):
        solve()


def printlist(a):
    for p in range(0, len(a)):
        out(str(a[p]) + ' ')




def factors(n):
    return set(reduce(list.__add__,
                      ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))









def solve():
    n,m=sep()
    ar=[]
    dx=[1,-1,0,0]
    dy=[0,0,1,-1]
    for i in range(n):
        t=inp()
        temp=[]
        for i in t:
            temp.append(i)
        ar.append(temp)
    def isvalid(i,j):
        if 0<=i<n and 0<=j<m:
            return 1
        return 0
    for i in range(n):
        for j in range(m):
            t=0
            k=ar[i][j]
            if k=="#":
                for move in range(4):
                    cur_x,cur_y=i+dx[move],j+dy[move]
                    if isvalid(cur_x,cur_y):
                        if ar[cur_x][cur_y]=="#":
                            t=1
                            break
                if t==0:
                    print("No")
                    quit()
    print("Yes")







#testcase(integer())
solve()

Submission status: Accepted

Solution code:
from itertools import product
H,W=map(int,input().split())
S=[input() for i in range(H)]
 
isOK=True
 
for y,x in product(range(H),range(W)):
    if S[y][x]=='.':
        continue
    sum=0
 
    if 0<x:
        if S[y][x-1]=='#':sum+=1
    
    if x<W-1:
        if S[y][x+1]=='#':sum+=1
    
    if 0<y:
        if S[y-1][x]=='#':sum+=1
    
    if y<H-1:
        if S[y+1][x]=='#':sum+=1
    
    if sum==0:
        isOK=False
 
if isOK:
    print("Yes")
else:
    print("No")

Submission status: Accepted

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

for h in range(H):
    c = 0
    for w in range(W):
        if S[h][w] == "#":
            c += 1
        else:
            if c == 1:
                cnt[h][w-1] = 1
            c = 0
    if c == 1:
        cnt[h][w] = 1

ans = "Yes"
for w in range(W):
    c = 0
    for h in range(H):
        if S[h][w] == "#":
            c += 1
        else:
            if c == 1:
                if cnt[h-1][w] == 1:
                    ans = "No"
                    break
            c = 0
    if c == 1:
        if cnt[h][w] == 1:
            ans = "No"
            break
            
print(ans)

Submission status: Accepted

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

ans = []
for row in src:
        ans.append(list(row))

dxy = [(1, 0), (-1, 0), (0, 1), (0, -1)]
for x in range(h):
        for y in range(w):
                if src[x][y] == ".":
                        continue
                if src[x][y] == "#":
                        flag = 0
                        for dx, dy in dxy:
                                if x + dx < 0 or x + dx > h -1 or y + dy < 0 or y + dy > w - 1:
                                        continue
                                if src[x + dx][y + dy] == "#":
                                        flag = 1
                                        break
                        if flag == 0:
                                print("No")
                                exit()

print("Yes")

Submission status: Accepted

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

isOK=True

for y,x in product(range(H),range(W)):
    if S[y][x]=='.':
        continue
    sum=0

    if 0<x:
        if S[y][x-1]=='#':sum+=1
    
    if x<W-1:
        if S[y][x+1]=='#':sum+=1
    
    if 0<y:
        if S[y-1][x]=='#':sum+=1
    
    if y<H-1:
        if S[y+1][x]=='#':sum+=1
    
    if sum==0:
        isOK=False

if isOK:
    print("Yes")
else:
    print("No")