Created
July 24, 2020 06:07
-
-
Save akshit0699/9877b3a38699d7a0d1bf79704a1e06f9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def maxDistance(self, grid): | |
rows = len(grid) | |
if rows == 0: | |
return -1 | |
cols = len(grid[0]) | |
lands = collections.deque() | |
maxDistance = 0 | |
# Cover up all the lands and say there nearest distance to themselves is = 0 | |
for i in range(rows): | |
for j in range(cols): | |
if grid[i][j] == 1: | |
lands.append([(i,j), 0]) | |
while lands: | |
for _ in range(len(lands)): | |
# Get the node and the distance value corresponding to it | |
temp = lands.popleft() | |
x,y = temp[0] | |
d = temp[1] | |
# Keep a global maxDistance check | |
maxDistance = max(maxDistance, d) | |
# Explore everything around the given land mass | |
for dx, dy in [(1,0), (-1,0), (0,1), (0,-1)]: | |
xx, yy = x + dx, y + dy | |
# Simple edge cases tested | |
if xx < 0 or xx == rows or yy < 0 or yy == cols: | |
continue | |
# If you find a sea around it | |
if grid[xx][yy] == 0: | |
# Mutate and append | |
grid[xx][yy] = d + 1 | |
lands.append([(xx, yy), d + 1]) | |
return maxDistance or -1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment