Re: [閒聊] 每日LeetCode已回收
1162. As Far from Land as Possible
題目:
給定一個只包含0 1的n*n方陣
0代表水且1代表陸地
找出所有水與陸地最短距離中的最大值
Example 1:
Input: grid = [[1,0,1],[0,0,0],[1,0,1]]
Output: 2
Explanation: The cell (1, 1) is as far as possible from all the land with distan
ce 2.
Example 2:
Input: grid = [[1,0,0],[0,0,0],[0,0,0]]
Output: 4
Explanation: The cell (2, 2) is as far as possible from all the land with distan
ce 4.
思路:
01 matrix的類似題
從陸地回推回去,將陸地的格子加進佇列
如果周邊4格有0,將為0的格子加入佇列並設為1代表已搜尋過
當所有佇列處理完即找到最遠的格子
要注意方陣全為1的case,會被搞到QQ
=================================
python code:
class Solution:
def maxDistance(self, grid: List[List[int]]) -> int:
row, col = len(grid), len(grid[0])
res = -1
que = deque()
for r in range(row) :
for c in range(col) :
if grid[r][c] == 1 :
que.append([r, c])
if len(que) == row*col : return res # no 0 exist
while que :
for _ in range(len(que)) :
r, c = que.popleft()
if r+1 < row and grid[r+1][c] == 0 :
grid[r+1][c] = 1
que.append([r+1, c])
if c+1 < col and grid[r][c+1] == 0 :
grid[r][c+1] = 1
que.append([r, c+1])
if r-1 >= 0 and grid[r-1][c] == 0 :
grid[r-1][c] = 1
que.append([r-1, c])
if c-1 >= 0 and grid[r][c-1] == 0 :
grid[r][c-1] = 1
que.append([r, c-1])
res += 1
return res
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 223.137.177.206 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1675997488.A.4E6.html
※ 編輯: umi0912umi (223.137.177.206 臺灣), 02/10/2023 10:52:48
→
02/10 11:33,
2年前
, 1F
02/10 11:33, 1F
→
02/10 15:59,
2年前
, 2F
02/10 15:59, 2F
討論串 (同標題文章)
完整討論串 (本文為第 226 之 719 篇):