파비의 매일매일 공부기록

2023.08.17 Today's Challenge 본문

Problem Solving/LeetCode

2023.08.17 Today's Challenge

fabichoi 2023. 8. 17. 23:45

https://leetcode.com/problems/01-matrix/

 

01 Matrix - LeetCode

Can you solve this real interview question? 01 Matrix - Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell. The distance between two adjacent cells is 1.   Example 1: [https://assets.leetcode.com/uploads/2021/04/24/01-1-g

leetcode.com

생각보다 조금 어려웠던 문제.
BFS로 풀어야 함.

class Solution:
    def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
        if not mat or not mat[0]:
            return []
        
        m, n = len(mat), len(mat[0])
        qu = deque()
        MAX_VALUE = m * n

        for i in range(m):
            for j in range(n):
                if mat[i][j] == 0:
                    qu.append((i, j))
                else:
                    mat[i][j] = MAX_VALUE
        
        dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]

        while qu:
            row, col = qu.popleft()
            for dr, dc in dirs:
                r, c = row + dr, col + dc
                if 0 <= r < m and 0 <= c < n and mat[r][c] > mat[row][col] + 1:
                    qu.append((r,c))
                    mat[r][c] = mat[row][col] + 1
        
        return mat
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.08.19 Today's Challenge  (0) 2023.08.19
2023.08.18 Today's Challenge  (0) 2023.08.18
2023.08.16 Today's Challenge  (0) 2023.08.16
2023.08.15 Today's Challenge  (0) 2023.08.15
2023.08.14 Today's Challenge  (0) 2023.08.14
Comments