Consider an n × m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. [Image] 

You're given a painted grid in the input. Tell Lenny if the grid is convex or not.


-----Input-----

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 50) — the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid.

It's guaranteed that the grid has at least one black cell.


-----Output-----

On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes.


-----Examples-----
Input
3 4
WWBW
BWWW
WWWB

Output
NO

Input
3 1
B
B
W

Output
YES

Source: codeforces | Difficulty: MEDIUM_HARD
Tags: Implementation

Constructive algorithms


Solutions:
(n, m) = list(map(int, input().split()))
(row, col_sum, row_sum, black) = ([], [], [], [])
for i in range(n):
	row.append(input())
	t = [0]
	for j in range(m):
		t += [t[j] + (row[i][j] == 'B')]
	row_sum += [t]
d = [[0, 1], [1, 0], [-1, 0], [0, -1]]
for i in range(n):
	for j in range(m):
		if row[i][j] is 'W':
			continue
		w = 0
		for di in d:
			x = i + di[0]
			y = j + di[1]
			if x < 0 or y < 0 or x >= n or (y >= m):
				w += 1
				continue
			if row[x][y] is 'W':
				w += 1
		if w > 0:
			black.append((i, j))
for i in range(m):
	t = [0]
	for j in range(n):
		t += [t[j] + (row[j][i] == 'B')]
	col_sum += [t]

def row_check(r, s, e):
	if s > e:
		(e, s) = (s, e)
	return row_sum[r][e + 1] - row_sum[r][s] == e - s + 1

def col_check(c, s, e):
	if s > e:
		(e, s) = (s, e)
	return col_sum[c][e + 1] - col_sum[c][s] == e - s + 1
res = True
for i in black:
	for j in black:
		if i <= j:
			continue
		a = row_check(i[0], i[1], j[1]) and col_check(j[1], i[0], j[0])
		b = row_check(j[0], i[1], j[1]) and col_check(i[1], i[0], j[0])
		res = res and (a or b)
print('YES' if res else 'NO')


import sys

def exi():
	print('NO')
	sys.exit()
I = lambda : list(map(int, input().split()))
g = []
(n, m) = I()
for i in range(n):
	g.append(list(input()))
for i in range(n):
	temp = 0
	for j in range(1, m):
		if g[i][j - 1] != g[i][j]:
			temp += 1
	if temp > 2 or (temp == 2 and g[i][0] == 'B'):
		exi()
for j in range(m):
	temp = 0
	for i in range(1, n):
		if g[i - 1][j] != g[i][j]:
			temp += 1
	if temp > 2 or (temp == 2 and g[0][j] == 'B'):
		exi()
for i1 in range(n):
	for j1 in range(m):
		if g[i1][j1] == 'B':
			for i2 in range(n):
				for j2 in range(m):
					if g[i2][j2] == 'B':
						if g[i1][j2] == 'W' and g[i2][j1] == 'W':
							exi()
print('YES')


import os
import sys
from io import BytesIO, IOBase
from collections import Counter
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')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)

def lcm(a, b):
	return a * b / gcd(a, b)

def main():
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		t = input()
		k = []
		for j in t:
			if j == 'W':
				k.append(0)
			if j == 'B':
				k.append(1)
		a.append(k)
	reach1 = [[] for i in range(2600)]
	blacks = []
	for i in range(n):
		for j in range(m):
			if a[i][j]:
				blacks.append(i * m + j)
				t = i
				while t >= 0 and a[t][j]:
					reach1[i * m + j].append(t * m + j)
					t -= 1
				t = i + 1
				while t < n and a[t][j]:
					reach1[i * m + j].append(t * m + j)
					t += 1
				t = j - 1
				while t >= 0 and a[i][t]:
					reach1[i * m + j].append(i * m + t)
					t -= 1
				t = j + 1
				while t < m and a[i][t]:
					reach1[i * m + j].append(i * m + t)
					t += 1
	f = 1
	for i in blacks:
		k = set(reach1[i])
		k.add(i)
		for j in reach1[i]:
			if j != i:
				for m in reach1[j]:
					k.add(m)
		for m in blacks:
			if m not in k:
				f = 0
				break
		if f == 0:
			break
	if f:
		print('YES')
	else:
		print('NO')
	return
main()


(n, m) = map(int, input().split())
grid = []
ans = True
for i in range(n):
	grid.append(input())
	black = False
	change = False
	for j in range(m):
		if grid[i][j] == 'W' and black:
			change = True
		elif grid[i][j] == 'B':
			if change and black:
				ans = False
			black = True
if not ans:
	print('NO')
	exit()
for j in range(m):
	black = False
	change = False
	for i in range(n):
		if grid[i][j] == 'W' and black:
			change = True
		elif grid[i][j] == 'B':
			if change and black:
				print('NO')
				exit()
			black = True
for i in range(n):
	for j in range(m):
		if grid[i][j] == 'B':
			for i_2 in range(n):
				for j_2 in range(m):
					if grid[i_2][j_2] == 'B' and grid[i][j_2] == 'W' and (grid[i_2][j] == 'W'):
						print('NO')
						exit()
print('YES')


def f():
	(n, m) = list(map(int, input().split()))
	t = [input() for j in range(n)]
	p = [''.join(i) for i in zip(*t)]
	if h(p):
		return 1
	i = 0
	while i < n and (not 'B' in t[i]):
		i += 1
	while i < n:
		a = t[i].find('B')
		if a < 0:
			i += 1
			break
		b = t[i].rfind('B')
		if 'W' in t[i][a:b + 1]:
			return 1
		for j in range(i + 1, n):
			if a > 0 and t[j][a - 1] == 'B' and (t[j][b] == 'W'):
				return 1
			if b < m - 1 and t[j][b + 1] == 'B' and (t[j][a] == 'W'):
				return 1
		i += 1
	while i < n:
		if 'B' in t[i]:
			return 1
		i += 1
	return 0

def h(t):
	(i, n) = (0, len(t))
	while i < n and (not 'B' in t[i]):
		i += 1
	while i < n:
		a = t[i].find('B')
		if a < 0:
			i += 1
			break
		b = t[i].rfind('B')
		if 'W' in t[i][a:b + 1]:
			return 1
		i += 1
	while i < n:
		if 'B' in t[i]:
			return 1
		i += 1
	return 0
print('YNEOS'[f()::2])


import sys
input = sys.stdin.readline

def check(x, y):
	for i in range(min(x[0], y[0]), max(x[0], y[0]) + 1):
		if not plan[i][x[1]] == 'B':
			return False
	for i in range(min(x[1], y[1]), max(x[1], y[1]) + 1):
		if not plan[y[0]][i] == 'B':
			return False
	return True
(n, m) = map(int, input().split())
plan = tuple((tuple((i for i in input().strip())) for j in range(n)))
start = [(i, j) for i in range(n) for j in range(m) if plan[i][j] == 'B']
for i in range(len(start)):
	for j in range(i + 1, len(start)):
		if not check(start[i], start[j]) and (not check(start[j], start[i])):
			print('NO')
			sys.exit()
print('YES')


(n, m) = map(int, input().split())
z = [[] for i in range(n + 1)]
for i in range(n):
	a = input()
	for j in a:
		z[i].append(j)

def solve(n, m):
	for i in range(n):
		cnt = 0
		for j in range(1, m):
			if z[i][j] != z[i][j - 1]:
				cnt += 1
		if cnt > 2:
			return 1
		if cnt == 2 and z[i][0] == 'B':
			return 1
	for j in range(m):
		cnt = 0
		for i in range(1, n):
			if z[i][j] != z[i - 1][j]:
				cnt += 1
		if cnt > 2:
			return 1
		if cnt == 2 and z[0][j] == 'B':
			return 1
	for i in range(n):
		for j in range(m):
			if z[i][j] == 'B':
				for x in range(i, n):
					for y in range(m):
						if z[x][y] == 'B':
							if z[i][y] == 'W' and z[x][j] == 'W':
								return 1
	return 0
print(['YES', 'NO'][solve(n, m)])


(n, m) = list(map(int, input().split()))
c = [input() for _ in ' ' * n]

def sol(n, m):
	for i in range(n):
		count = 0
		for j in range(1, m):
			if c[i][j] != c[i][j - 1]:
				count += 1
		if count > 2:
			return False
		if count == 2 and c[i][0] == 'B':
			return False
	for j in range(m):
		count = 0
		for i in range(1, n):
			if c[i][j] != c[i - 1][j]:
				count += 1
		if count > 2:
			return False
		if count == 2 and c[0][j] == 'B':
			return False
	for i in range(n):
		for j in range(m):
			if c[i][j] == 'B':
				for x in range(i, n):
					for y in range(m):
						if c[x][y] == 'B':
							if c[i][y] == 'W' and c[x][j] == 'W':
								return False
	return True
print('NYOE S'[sol(n, m)::2])


def solve(n, m):
	grid = []
	for i in range(n):
		grid.append(input().strip())
		cnt = 0
		for j in range(1, m):
			if grid[i][j] != grid[i][j - 1]:
				cnt += 1
		if cnt > 2 or (cnt == 2 and grid[i][0] == 'B'):
			return False
	for j in range(m):
		cnt = 0
		for i in range(1, n):
			if grid[i][j] != grid[i - 1][j]:
				cnt += 1
		if cnt > 2 or (cnt == 2 and grid[0][j] == 'B'):
			return False
	bps = []
	for i in range(n):
		for j in range(m):
			if grid[i][j] == 'B':
				bp1 = (i, j)
				for k in range(len(bps)):
					bp2 = bps[k]
					if not (grid[bp1[0]][bp2[1]] == 'B' or grid[bp2[0]][bp1[1]] == 'B'):
						return False
				bps.append((i, j))
	return True
(n, m) = map(int, input().strip().split())
ans = solve(n, m)
if ans:
	print('YES')
else:
	print('NO')