-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasFarfromLandasPossible.py
More file actions
34 lines (31 loc) · 1 KB
/
asFarfromLandasPossible.py
File metadata and controls
34 lines (31 loc) · 1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Source: https://leetcode.com/problems/as-far-from-land-as-possible/
# Author: Miao Zhang
# Date: 2021-04-15
class Solution:
def maxDistance(self, grid: List[List[int]]) -> int:
m = len(grid)
n = len(grid[0])
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
res = -1
q = collections.deque()
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
q.append((i, j))
steps = 0
while q:
qlen = len(q)
for _ in range(qlen):
i, j = q.popleft()
if grid[i][j] == 2:
res = max(res, steps)
for d in dirs:
x = i + d[0]
y = j + d[1]
if x < 0 or x >= m or y < 0 or y >= n or grid[x][y] != 0: continue
grid[x][y] = 2
q.append((x, y))
steps += 1
return res