# python program for the above approach
import math
M = 1000000000 + 7
# Stores the moves in the matrix
directions = [[0, 1], [-1, 0], [0, -1],
[1, 0], [1, 1], [-1, -1],
[-1, 1], [1, -1]]
# Function to find if the current cell
# lies in the matrix or not
def isInside(i, j, N, M):
if (i >= 0 and i < N and j >= 0 and j < M):
return True
return False
# Function to perform the DFS Traversal
def DFS(mat, N, M, i, j, visited):
if (visited[i][j] == True):
return
visited[i][j] = True
# Iterate over the direction vector
for it in directions:
I = i + it[0]
J = j + it[1]
if (isInside(I, J, N, M)):
if (mat[I][J] == 0):
# DFS Call
DFS(mat, N, M, I, J, visited)
# Function to check if it satisfy the
# given criteria or not
def check(N, M, mat):
# Keeps the count of cell having
# value as 0
black = 0
for i in range(0, N):
for j in range(0, M):
if (mat[i][j] == 0):
black += 1
# If condition doesn't satisfy
if (black < 2 * (max(N, M))):
print("NO")
return
visited = []
for i in range(0, N):
temp = []
for j in range(0, M):
temp.append(False)
visited.append(temp)
# Keeps the track of unvisited cell
# having values 0
black_spots = 0
for i in range(0, N):
for j in range(0, M):
if (visited[i][j] == False and mat[i][j] == 0):
# Increasing count of
# black_spot
black_spots += 1
DFS(mat, N, M, i, j, visited)
# Find the GCD of N and M
T = math.gcd(N, M)
# Print the result
if black_spots >= T:
print("Yes")
else:
print("No")
# Driver Code
if __name__ == "__main__":
N = 3
M = 3
mat = [[0, 0, 1], [1, 1, 1], [0, 0, 1]]
check(M, N, mat)
# This code is contributed by rakeshsahni