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: Wrong Answer

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

sharp_counter = 0
for h in range(H):
    for w in range(W):
        if grid[h][w] == ".":
            continue

        sharp_counter += 1
        nearby_sharp_counter = 0
        for a, b in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
            if h+a < 0 or h+a >= H or w+b < 0 or w+b >= W:
                continue
            elif grid[h+a][w+b] == "#":
                nearby_sharp_counter += 1
        
        if nearby_sharp_counter == 0:
            print("No")
            exit()

if sharp_counter == 0:
    print("No")
    exit()

print("Yes")

Submission status: Wrong Answer

Solution code:
H, W = list(map(int, input().split()))
S = [input() for _ in range(H)]
field = [[0 for w in range(W+2)] for h in range(H+2)]

def add(h, w):
    field[h][w + 1] += 1
    field[h + 2][w + 1] += 1
    field[h + 1][w] += 1
    field[h + 1][w + 2] += 1

for h in range(H):
    for w in range(W):
        if S[h][w] == "#":
            add(h, w)
        else:
            field[h+1][w+1] -= 10
        
res = 0
for l in field[1:W-1]:
    if 0 in l[1:H-1]:
        print("No") 
        break
else:
    print("Yes")

Submission status: Wrong Answer

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

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

ans=True
for i in range(H):
  for j in range(W):
    if M[i][j]=='#':
      if (j+1 < W-1 and M[i][j+1]=='#') or  (i+1 < H-1 and M[i+1][j]=='#') or (j-1 >= 0 and M[i][j-1]=='#') or (i-1 >=0 and M[i-1][j]=='#'):
        continue
      else:
        ans=False
        break
if ans:
  print("Yes")
else:
  print("No")

Submission status: Wrong Answer

Solution code:
h,w=map(int,input().split())
canvas=['.'+input()+'.'  for i in range(h)]
canvas.append('.'*(w+2))
canvas.insert(0,'.'*(w+2))

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

Submission status: Wrong Answer

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

result = True

def check(i, j):
  if board[i][j] == '.':
    return True
  
  if i == 0:
    if j == 0:
      if board[i][j + 1] == '.' and board[i + 1][j] == '.':
        return False
    elif j == w - 1:
      if board[i][j - 1] == ',' and board[i + 1][j] == '.':
        return False
    else:
      if board[i][j - 1] == ',' and board[i][j + 1] == '.' and board[i + 1][j] == '.':
        return False
  elif i == h - 1:
    if j == 0:
      if board[i][j + 1] == '.' and board[i - 1][j] == '.':
        return False
    elif j == w - 1:
      if board[i][j - 1] == ',' and board[i - 1][j] == '.':
        return False
    else:
      if board[i][j - 1] == ',' and board[i][j + 1] == '.' and board[i - 1][j] == '.':
        return False
  else:
    if j == 0:
      if board[i][j + 1] == '.' and board[i - 1][j] == '.' and board[i + 1][j] == '.':
        return False
    elif j == w - 1:
      if board[i][j - 1] == ',' and board[i - 1][j] == '.' and board[i + 1][j] == '.':
        return False
    else:
      if board[i][j - 1] == ',' and board[i][j + 1] == '.' and board[i - 1][j] == '.' and board[i + 1][j] == '.':
        return False

  return True

for i in range(h):
  for j in range(w):
    result = check(i, j)
    if not result:
      break
  if not result:
    break

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

Submission status: Wrong Answer

Solution code:
def solve(table, H, W):
    def is_ok(row, col):
        if not table[row][col]:
            return True
        if row > 1 and table[row - 1][col] or row + 1 < H and table[row + 1][col]:
            return True
        if col > 1 and table[row][col - 1] or col + 1 < W and table[row][col + 1]:
            return True
        return False

    for row in range(H):
        for col in range(W):
            if not is_ok(row, col):
                return False
    return True


H, W = map(int, input().split())
table = []
for r in range(H):
    table.append(list(map(lambda x: x == "#", list(input()))))

print("Yes" if solve(table, H, W) else "No")

Submission status: Wrong Answer

Solution code:
import sys

def sub(field, x, y):
  if y < 0 or x < 0 or y >= len(field) or x >= len(field[y]):
    return True
  if field[y][x] != '#':
    return False
  return True

def isok(field, x, y):
  units = [(0, 1), (1, 0), (0, -1), (-1, 0)]
  for unit in units:
    _x = x + unit[0]
    _y = y + unit[1]
    if not sub(field, _x, _y):
      return False
  return True

l = sys.stdin.readline()
xy = [int(x) for x in l.rstrip('\n').split(' ')]
height = xy[0]
width = xy[1]

field = []
for _ in xrange(height):
  field.append(sys.stdin.readline())

for y in xrange(len(field)):
  for x in xrange(len(field[y])):
    if not isok(field, x, y):
      print 'No'
      exit()
print 'Yes'

Submission status: Wrong Answer

Solution code:
def inpl(): return list(map(int, input().split()))
H, W = inpl()
s = ['.'*(W+2)]
for i in range(H):
    s.append('.'+input()+'.')
s.append('.'*(W+2))

end = 0
dxy = [[1,0],[0,1],[-1,0],[0,-1]]
for i in range(1,H+1):
    for j in range(1,W+1):
        for k in dxy:
            if s[i+k[0]][j+k[1]]=='#':
                break
        else:
            end = 1
            break
    if end == 1:
        break
if end == 1:
    print('No')
else:
    print('Yes')

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**6)
h,w=map(int,input().split())
c=[list(input()) for i in range(h)]
dxy=((0,1),(0,-1),(1,0),(-1,0))
def dfs(y,x):
    c[y][x]="."
    for dx,dy in dxy:
        nx,ny=x+dx,y+dy
        if 0<=nx<=w-1 and 0<=ny<=h-1 and c[ny][nx]=="#":
            dfs(ny,nx)
    return       
for i in range(w):
    for j in range(h):
        if c[j][i]=="#":
            dfs(j,i)
for i in range(w):
    for j in range(h):
        if c[j][i]=="#":
            print("No")
            sys.exit()
print("Yes")

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**6)
h,w=map(int,input().split())
c=[list(input()) for i in range(h)]
dxy=((0,1),(0,-1),(1,0),(-1,0))
def dfs(y,x):
    c[y][x]="#"
    for dx,dy in dxy:
        nx,ny=x+dx,y+dy
        if 0<=nx<=w-1 and 0<=ny<=h-1 and (c[ny][nx]=="." or c[ny][nx]=="g"):
            dfs(ny,nx)
    return       
for i in range(w):
    for j in range(h):
        if c[j][i]=="#":
            dfs(j,i)
for i in range(w):
    for j in range(h):
        if c[j][i]=="#":
            print("No")
            sys.exit()
print("Yes")

Submission status: Wrong Answer

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

ans = "Yes"
for i in range(h):
    for j in range(w):
        if s[i][j] == '#':
            ok = False
            if 1 < i and s[i - 1][j] == '#':
                ok = True
            if i + 1 < h and s[i + 1][j] == '#':
                ok = True
            if 1 < j and s[i][j - 1] == '#':
                ok = True
            if j + 1 < w and s[i][j + 1] == '#':
                ok = True
            if not ok:
                ans = "No"
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**6)
h,w=map(int,input().split())
c=[list(input()) for i in range(h)]
dxy=((0,1),(0,-1),(1,0),(-1,0))
def dfs(y,x):
    c[y][x]="#"
    for dx,dy in dxy:
        nx,ny=x+dx,y+dy
        if 0<=nx<=w-1 and 0<=ny<=h-1 and (c[ny][nx]=="." or c[ny][nx]=="g"):
            dfs(ny,nx)
    return       
for i in range(w):
    for j in range(h):
        if c[j][i]=="s":
            dfs(j,i)
for i in range(w):
    for j in range(h):
        if c[j][i]=="g":
            print("No")
            sys.exit()
print("Yes")

Submission status: Time Limit Exceeded

Solution code:
# C - Grid Repainting 2
from collections import deque

H, W = map(int, input().split())
grid = [[''] * W for _ in range(H)]
for i in range(H):
    grid[i] = list(str(input()))

d = deque()
ans = 'Yes'
for i in range(H):
    for j in range(W):
        d.append((i, j))
        tmp = 0
        while d:
            p, q = d.popleft()
            if grid[p][q] == '#':
                grid[p][q] = '.'
                tmp += 1
            for x, y in ((0, 1), (1, 0), (1, 0), (0, -1)):
                nx = p+x
                ny = q+y
                if nx < 0 or nx >= H or ny < 0 or ny >= W:
                    continue
                if grid[nx][ny] == '.':
                    continue
                d.append((nx, ny))
        if tmp == 1:
            ans = 'No'
            break
    else:
        continue
    break
print(ans)

Submission status: Time Limit Exceeded

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 bfs((j, i)) == 1:
            ans = 'No'
            break
print(ans)

Submission status: Time Limit Exceeded

Solution code:
h, w = map(int, input().split())
s = [input() for i in range(h)]
isCase = True
count = 1

while (count != 0):
    count = 0
    for i in range(h):
        for j in range(w):
            count = s[i][j].count('#')
            if (s[i][j] == '#'):
                s[i][j].replace('#', '.')
                if (s[max(i-1,0)][j] == '#'):
                    s[max(i-1,0)][j].replace('#', '.')
                elif (s[i][max(j-1,0)] == '#'):
                    s[i][max(j-1,0)].replace('#', '.')
                elif (s[i][min(j+1,w-1)] == '#'):
                    s[i][min(j+1,w-1)].replace('#', '.')
                elif (s[min(i+1,h-1)][j] == '#'):
                    s[min(i+1,h-1)][j].replace('#', '.')
                else:
                    isCase = False
                    break
    if (isCase == False):
        break

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

Submission status: Time Limit Exceeded

Solution code:
def main():
	H, W = map(int, input().split())
	S = [""]*H
	visit = [[False for _ in range(W)] for _ in range(H) ]
	for i in range(H):
		S[i] = input()

	stack = []
	for i in range(H):
		for j in range(W):
			if visit[i][j]:
				continue
			stack.append([i, j])
			while stack:
				current = stack.pop()
				if S[current[0]][current[1]] == ".":
					continue

				if current[1] < W-1 and S[current[0]][current[1]+1] == "#":
					stack.append([current[0], current[1]+1])
					visit[current[0]][current[1]+1] = True
					visit[current[0]][current[1]] = True
				if current[0] < H-1 and S[current[0]+1][current[1]] == "#":
					stack.append([current[0]+1, current[1]])
					visit[current[0]+1][current[1]] = True
					visit[current[0]][current[1]] = True

			if S[i][j] == "#" and not visit[i][j]:
				print("No")
				return

	print("Yes")


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
	H, W = map(int, input().split())
	S = [""]*H
	visit = [[False for _ in range(W)] for _ in range(H) ]
	for i in range(H):
		S[i] = input()

	stack = []
	for i in range(H):
		for j in range(W):
			if visit[i][j]:
				continue
			stack.append([i, j])
			while stack:
				current = stack.pop()
				if S[current[0]][current[1]] == ".":
					continue

				if current[1] < W-1 and S[current[0]][current[1]+1] == "#":
					stack.append([current[0], current[1]+1])
					visit[current[0]][current[1]+1] = True
					visit[current[0]][current[1]] = True
				if current[0] < H-1 and S[current[0]+1][current[1]] == "#":
					stack.append([current[0]+1, current[1]])
					visit[current[0]+1][current[1]] = True
					visit[current[0]][current[1]] = True

	for i in range(H):
		for j in range(W):
			if S[i][j] == "#":
				if not visit[i][j]:
					print("No")
					return


	print("Yes")



if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
	H, W = map(int, input().split())
	S = [""]*H
	visit = [[False for _ in range(W)] for _ in range(H) ]
	for i in range(H):
		S[i] = input()

	stack = []
	for i in range(H):
		for j in range(W):
			stack.append([i, j])
			while stack:
				current = stack.pop()
				if S[current[0]][current[1]] == ".":
					continue

				if current[1] < W-1 and S[current[0]][current[1]+1] == "#":
					stack.append([current[0], current[1]+1])
					visit[current[0]][current[1]+1] = True
					visit[current[0]][current[1]] = True
				if current[0] < H-1 and S[current[0]+1][current[1]] == "#":
					stack.append([current[0]+1, current[1]])
					visit[current[0]+1][current[1]] = True
					visit[current[0]][current[1]] = True

	for i in range(H):
		for j in range(W):
			if S[i][j] == "#":
				if not visit[i][j]:
					print("No")
					return


	print("Yes")



if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
import queue

def search(h,w):
  global arr

  c_max=1
  q=queue.Queue()
  q.put((h,w,1))
  while not q.empty():
    h,w,c=q.get()
    if c_max<c:
      c_max=c

    arr[h][w]="."

    if h>=1 and arr[h-1][w]=="#":
      q.put((h-1,w,c+1))
    if h<=len(arr)-2 and arr[h+1][w]=="#":
      q.put((h+1,w,c+1))
    if w>=1 and arr[h][w-1]=="#":
      q.put((h,w-1,c+1))
    if w<=len(arr[h])-2 and arr[h][w+1]=="#":
      q.put((h,w+1,c+1))

  return c_max

H,W=list(map(int,input().split(" ")))
arr=[]
for z in range(H):
  arr.append(list(input()))

h,w=0,0

while True:

  if arr[h][w]=="#":
    if search(h,w)==1:
      print("No")
      sys.exit()

  w+=1
  if w>=W:
    w=0
    h+=1
  if h>=H:
    break

print("Yes")

Submission status: Time Limit Exceeded

Solution code:
import sys
import queue

def search(h,w):
  global arr

  c_max=1
  q=queue.Queue()
  q.put((h,w,1))
  while not q.empty():
    h,w,c=q.get()
    if c_max<c:
      c_max=c

    arr[h][w]="."

    if h>=1 and arr[h-1][w]=="#":
      q.put((h-1,w,c+1))
    if h<=len(arr)-2 and arr[h+1][w]=="#":
      q.put((h+1,w,c+1))
    if w>=1 and arr[h][w-1]=="#":
      q.put((h,w-1,c+1))
    if w<=len(arr[h])-2 and arr[h][w+1]=="#":
      q.put((h,w+1,c+1))

  return c_max



H,W=list(map(int,input().split(" ")))
arr=[]
for z in range(H):
  arr.append(list(input()))

h,w=0,0

while True:

  if arr[h][w]=="#":
    if search(h,w)==1:
      print("No")
      sys.exit()

  w+=1
  if w==W:
    w=0
    h+=1
  if h==H:
    break

print("Yes")

Submission status: Time Limit Exceeded

Solution code:
import sys

def rec_function(i, j, lasting):
    check_list[i][j] = 1

    if (not lasting) and \
       (not (i < H - 1 and s_list[i+1][j] == "#")) and \
       (not (j < W - 1 and s_list[i][j+1] == "#")):
        global impossible
        impossible = True
        return

    if i < H - 1 and s_list[i+1][j] == "#":
        rec_function(i + 1, j, True)
    if j < W - 1 and s_list[i][j+1] == "#":
        rec_function(i, j + 1, True)



H, W = list(map(int, input().split()))
s_list = list()
check_list = [[0]*W]*H
impossible = False

for _ in range(H):
    s = input()
    s_list.append(s)

for i in range(H):
    for j in range(W):
        if check_list[i][j] == 1:
            continue

        if s_list[i][j] == '.':
            check_list[i][j] = 1
            continue

        rec_function(i, j, False)
        
        if impossible:
            print('No')
            sys.exit()

print('Yes')

Submission status: Time Limit Exceeded

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

ans = True
for i in range(h):
    for j in range(w):
        if field[i][j] == '#':
            temp = 0
            que = list()
            que.append((i, j))
            while que:
                x, y = que.pop(0)
                temp += 1
                string = list(field[x])
                string[y] = '.'
                field[x] = ''.join(string)
                dd = [(1, 0), (-1, 0), (0, 1), (0, -1)]
                for ddd in dd:
                    dx, dy = ddd
                    nx, ny = x + dx, y + dy
                    if nx >= 0 and nx < h and ny >= 0 and ny < w and field[nx][ny] == '#':
                        que.append((nx, ny))
            if temp == 1:
                ans = False
                break

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

Submission status: Accepted

Solution code:
import sys
import math
from collections import defaultdict, deque, Counter
from copy import deepcopy
from bisect import bisect, bisect_right, bisect_left
from heapq import heapify, heappop, heappush
    
input = sys.stdin.readline
def RD(): return input().rstrip()
def F(): return float(input().rstrip())
def I(): return int(input().rstrip())
def MI(): return map(int, input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int, input().split()))
def TI(): return tuple(map(int, input().split()))
def LF(): return list(map(float,input().split()))
def Init(H, W, num): return [[num for i in range(W)] for j in range(H)]
    
    
def main():
    H, W = MI()
    D = Init(H, W, -1)
    L = [input().rstrip() for i in range(H)]
    move = [[1,0],[0,1],[-1,0],[0,-1]]
    for i in range(H):
        for j in range(W):
            if L[i][j] == "#" and D[i][j] == -1:
                D[i][j] = 0
                dq = deque([(i, j)])
                while dq:
                    x, y = dq.popleft()
                    for x1, y1 in move:
                        x1+=x
                        y1+=y
                        if x1 >= 0 and x1 <= H-1 and y1 >= 0 and y1 <= W-1 and D[x1][y1] == -1:
                            if L[x1][y1] == "#":
                                D[x1][y1] = D[x][y]+1
                                dq.append((x1, y1))
                if D[x][y] == 0:
                    print("No")
                    exit()
    print("Yes")

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
S = [["."]*(w+2)]
for i in range(h):
  S.append(["."]+list(input())+["."])
S.append(["."]*(w+2))
for i in range(h+2):
  for j in range(w+2):
    if S[i][j] == "#":
      if S[i+1][j] == "." and S[i-1][j] == "." and S[i][j+1] == "." and S[i][j-1] == ".": 
        print("No")
        quit()
print("Yes")

Submission status: Accepted

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

canvas = []

for i in range(H):
  canvas.append(list(input()))
  
#print(canvas)
for i in range(H):
  for j in range(W):
    cnt = 0
    if canvas[i][j] == "#":
      for h in range(-1,2):
        for w in range(-1,2):
          if canvas[min(max(i+h,0),H-1)][min(max(j+w,0),W-1)]=="#" and (abs(h)+abs(w))%2==1:
            cnt+=1
      if cnt==0:
        print("No")
        exit()
print("Yes")

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
S = []
D = [[-1, 0], [0, -1], [1, 0], [0, 1]]
for i in range(H):
  S.append(input())
f = 0
for i in range(H):
  for j in range(W):
    if S[i][j] == "#":
      g = 0
      for k in range(4):
        if 0 <= i + D[k][0] < H and 0 <= j + D[k][1] < W and S[i+D[k][0]][j+D[k][1]] == "#":
          g = 1
      if g == 0:
        f = 1
if f == 0:
  print("Yes")
else:
  print("No")

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
L = ['.' + input() + '.' for _ in range(H)]
L = ['.' * (W + 2)] + L + ['.' * (W + 2)]
for i in range(1, H + 1):
  for j in range(1, W + 1):
    if L[i][j] == "#":
      l = [L[i-1][j], L[i+1][j], L[i][j-1], L[i][j+1]]
      if '#' not in l:
        print('No')
        break
  else:
    continue
  break
else:
  print('Yes')

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
grid = []
ans = "Yes"

for _ in range(H):
  grid_i = input().split()
  grid.append(grid_i[0])

for i in range(H):
  for j in range(W):
    if grid[i][j] == "#":
      X = "NG"
      if (i-1 >= 0 and grid[i-1][j] == ".") or i < 1:
        None
      else:
        X = "OK"
      if (j-1 >= 0 and grid[i][j-1] == ".") or j < 1:
        None
      else:
        X = "OK"
      if (i+1 < H and grid[i+1][j] == ".") or i+1 >= H:
        None
      else:
        X = "OK"
      if (j+1 < W and grid[i][j+1] == ".") or j+1 >= W:
        None
      else:
        X = "OK"
      if X == "NG":
        ans = "No"

print(ans)

Submission status: Accepted

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

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

for i in range(H):
    for j in range(W):
        
        if l[i][j] == '.':
            pass
        else:
            count = 0
            if i > 0 and l[i-1][j] == '#':
                    count += 1 #上方向
            if i < (H-1) and l[i+1][j] == '#':
                count += 1     #下方向
            if j > 0 and l[i][j-1] == '#':
                count += 1     #左方向
            if j < (W-1) and l[i][j+1] == '#':
                count += 1     #右方向
            if count == 0:
                print('No')
                sys.exit()
                
print('Yes')

Submission status: Accepted

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

def get(lst, i, default=None):
  try:
    return lst[i]
  except IndexError:
    return default

for i in range(H):
  for j in range(W):
    s = SS[i][j]
    if s == '#':
      if '#' not in [get(get(SS, i-1, []), j), get(get(SS, i, []), j-1), get(get(SS, i+1, []), j), get(get(SS, i, []), j+1)]:
        print('No')
        import sys
        sys.exit()

print('Yes')

Submission status: Accepted

Solution code:
col,row = [int(x) for x in input().split()]
map_list = [[0] * (row+2)]
for i in range(col):
    map_list.append(["0"] + list(input()) + ["0"])
map_list.append(map_list[0])
#print(map_list)

def check(x,y):
    lands = [[x,y]]
    #print(lands)
    area = 0
    sealine = 0
    while lands:
        #print(area)
        #print(lands)
        x,y = lands.pop()
        #print(x,y)
        area += 1
        map_list[y][x] = "2"
        if map_list[y+1][x] == "#":
            lands.append([x,y+1])
        elif not map_list[y+1][x] == "2":
            sealine += 1
        if map_list[y][x+1] == "#":
            lands.append([x+1,y])
        elif not map_list[y][x+1] == "2":
            sealine += 1
        if map_list[y-1][x] == "#":
            lands.append([x,y-1])
        elif not map_list[y-1][x] == "2":
            sealine += 1
        if map_list[y][x-1] == "#":
            lands.append([x-1,y])
        elif not map_list[y][x-1] == "2":
            sealine += 1
        lands = list(map(tuple,lands))
        lands = list(set(lands))
        #print(lands)
    return area

res = "Yes"
for i in range(1,col+1):
    for j in range(1,row+1):
        if map_list[i][j] == "#":
            if check(j,i) == 1:
              res = "No"
print(res)

Submission status: Accepted

Solution code:
import sys

def check(i,j,s_list,h,w):
    uesita_list = [-1,1]
    sayuu_list = [-1,1]

    for uesita in uesita_list:
        new_i = i + uesita
        if new_i < 0 or new_i > h-1:
            continue
        if s_list[new_i][j] == "#":
            return True

    for sayuu in sayuu_list:
        new_j = j + sayuu
        if new_j > w-1 or new_j < 0:
            continue
        if s_list[i][new_j] == "#":
            return True
    
    return False            


input = sys.stdin.readline

h, w= map(int, input().split())

s_list = [[0 for _ in range(w)] for _ in range(h)]
for i in range(h):
    w_s_list = input()
    w_s_list = w_s_list.replace('\n','')
    w_s_list = list(w_s_list)
    for j in range(w):
        s_list[i][j] = w_s_list[j]


for i in range(h):
    for j in range(w):
        s = s_list[i][j]
        if s == "#":
            ok_flag = check(i,j,s_list,h,w)
            if not ok_flag:
                print("No")
                exit(0)

print("Yes")

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))
ans="Yes"
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][j+1]=="." and s[i+1][j]=="." and s[i][j-1]==".":
        ans="No"
        break
print(ans)

Submission status: Accepted

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

for i in range(h):
  for j in range(w):
    cnt = 0
    if F[i][j] == '#':
      if 0 <= (i-1) < h: 
        if F[i-1][j] == '#': cnt += 1
      if 0 <= (i+1) < h: 
        if F[i+1][j] == '#': cnt += 1
      if 0 <= (j-1) < w:
        if F[i][j-1] == '#': cnt += 1
      if 0 <= (j+1) < w:
        if F[i][j+1] == '#': cnt += 1
      if cnt == 0:
        print('No')
        exit()
print('Yes')

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
S = [["."] * (W+2)]
for i in range(H):
    S.append(list("."+input().rstrip()+"."))
S.append(["."]*(W+2))
#print(S)

def checkaround(i,j):
    dirc = [[0,1],[-1,0],[0,-1],[1,0]]
    for d in dirc:
        if S[i-d[0]][j-d[1]] == "#":
            return True
    return False
def main():
    for i in range(1,H+1):
        for j in range(1,W+1):
            if S[i][j] == "#":
                if not checkaround(i,j):
                    print("No")
                    return
    print("Yes")

main()

Submission status: Accepted

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

def check(H, W, s, x, y):
    res = False
    if x - 1 >= 0 and s[y][x-1] == '#':
        res = True
    if x + 1 < W and s[y][x+1] == '#':
        res = True
    if y - 1 >= 0 and s[y-1][x] == '#':
        res = True
    if y + 1 < H and s[y+1][x] == '#':
        res = True

    return res


H,W = map(int, input().split())
s = []
for h in range(H):
    s.append(list(input()))

for y in range(H):
    for x in range(W):
        if s[y][x] == "#" and not check(H, W, s, x, y):
            print("No")
            exit()

print("Yes")

Submission status: Accepted

Solution code:
from itertools import product
from collections import deque
import numpy as np
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]) + '\n'
    def __getitem__(self, x):
        return self.grid[x]
    def __setitem__(self, x, val):
        self.grid[x] = val


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

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

for y, x in product(range(h), range(w)):
    if grid[y, x] == '#':
        if len(list(dfs(grid, (x, y)))) == 1:
            print('No')
            break
else:
    print('Yes')

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 18 10:13:51 2020

@author: liang
"""
H, W = map(int, input().split())
flag = True
field = [input() for i in range(H)]

for i in range(H):
    for j in range(W):
        if field[i][j] == "#":
            tmp = False
            if i-1>= 0 and field[i-1][j] == "#":
                tmp = True
            if i+1 < H and field[i+1][j] == "#":
                tmp = True
            if j-1>= 0 and field[i][j-1] == "#":
                tmp = True
            if j+1 < W and field[i][j+1] == "#":
                tmp = True
            if tmp == False:
                flag = False

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