Google Interview Question
Java DevelopersCountry: United States
def check_surrounded(black_positions, white_positions):
"""
black_positions is a list of positions: [(row1, col1), (row2, col2), ...]
white_positions is a list of positions: [(row1, col1), (row2, col2), ...]
"""
POSITIONS = {}
for position in black_positions:
POSITIONS[position] = 'B'
for position in white_positions:
POSITIONS[position] = 'B'
for row, col in white_positions:
if (row - 1, col) not in POSITIONS or \
(row + 1, col) not in POSITIONS or \
(row, col + 1) not in POSITIONS or \
(row, col - 1) not in POSITIONS:
return False
return True
If surrounded means "surrounded from 4 sides" and excludes white chess pieces on the boundary, you can find the answer in the article "Count all 0s which are blocked by 1s in binary matrix" on geekforgeeks:
- Idea is based on the DFS. First we remove all the zero value cells in the matrix which are reachable from boundary of Matrix using DFS. After that we count all zeros which are left in binary matrix.
If each location have index of x and y then if each white chess x is between at least two black chesses x with same y and each white chess y is between at least two black chess with same x then that chess is surrounded by black chesses.
- nooreddin February 14, 20181. Sort all black chesses by x in array A in O(n lg n) time.
2. Sort all black chesses by y in array B in O(n lg n) time.
3. For each white chess search for its x in the first array in O(lg n). Compare y of this white chess with y of all matched y chesses ( in worst case it takes O(n) ). If it is between at least two of them then do the same process for x. If either of these cases does not match then ignore this chess. Otherwise continue to the next chess.
If there are n black chess and m white chess then the worse case running time of the algorithm is O( n lg n + n m ).