From 260cc00a608a681791ace02b6c25be4a5bc2ebe5 Mon Sep 17 00:00:00 2001 From: JiayangWu <530081999@qq.com> Date: Sun, 29 Mar 2020 01:16:44 -0400 Subject: [PATCH] 2020-03-29 --- ...60\345\233\276\345\210\206\346\236\220.py" | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 "1162.\345\234\260\345\233\276\345\210\206\346\236\220/1162-\345\234\260\345\233\276\345\210\206\346\236\220.py" diff --git "a/1162.\345\234\260\345\233\276\345\210\206\346\236\220/1162-\345\234\260\345\233\276\345\210\206\346\236\220.py" "b/1162.\345\234\260\345\233\276\345\210\206\346\236\220/1162-\345\234\260\345\233\276\345\210\206\346\236\220.py" new file mode 100644 index 0000000..b1dbb0c --- /dev/null +++ "b/1162.\345\234\260\345\233\276\345\210\206\346\236\220/1162-\345\234\260\345\233\276\345\210\206\346\236\220.py" @@ -0,0 +1,38 @@ +class Solution(object): + def maxDistance(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + from collections import deque + m, n = len(grid), len(grid[0]) + land = [] + for i in range(m): + for j in range(n): + if grid[i][j] == 1: + land.append((i, j)) + + if not land or len(land) == m * n: + return -1 + + res = 0 + dx = [1, -1, 0, 0] + dy = [0, 0, 1, -1] + + queue = deque(land) + visited = set(land) + while queue: + for _ in range(len(queue)): + x0, y0 = queue.popleft() + + for k in range(4): + x = x0 + dx[k] + y = y0 + dy[k] + + if 0 <= x < m and 0 <= y < n and grid[x][y] == 0 and (x, y) not in visited: + queue.append((x, y)) + visited.add((x, y)) + res += 1 + return res - 1 + + \ No newline at end of file