이 영역을 누르면 첫 페이지로 이동
butter_shower 블로그의 첫 페이지로 이동

butter_shower

페이지 맨 위로 올라가기

butter_shower

[LeetCode] 542. 01 Matrix - BFS

  • 2020.10.15 21:20
  • 알고리즘 Algorithm /PS
글 작성자: _rian

문제 링크 : https://leetcode.com/problems/01-matrix/

 

01 Matrix - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

01 Matrix - LeetCode

Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.

The distance between two adjacent cells is 1.

Example 1

Input:
[[0,0,0],
 [0,1,0],
 [0,0,0]]

Output:
[[0,0,0],
 [0,1,0],
 [0,0,0]]

Example 2

Input:
[[0,0,0],
 [0,1,0],
 [1,1,1]]

Output:
[[0,0,0],
 [0,1,0],
 [1,2,1]]

Note

  1. The number of elements of the given matrix will not exceed 10,000.
  2. There are at least one 0 in the given matrix.
  3. The cells are adjacent in only four directions: up, down, left and right.

풀이

  1. 0이 아닌 좌표를 발견했을 때 0이 해당 지점에서 얼마나 떨어져있는지를 BFS를 통해 찾으면 되는 문제!
from collections import deque
class Solution:
    def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]:

        def find_nearest0(i, j, matrix, level):

            q = deque()
            q.append([level, [i, j]]) # q에 레벨, (i, j) 좌표가 들어간다

            n_c = [-1, 0, 1, 0]
            n_r = [0, -1, 0, 1]
            res = 0

            while q:
                l, a = q.popleft()
                ni, nj = a[0], a[1]

                if matrix[ni][nj] == 0:
                    res = l
                    break

                for i in range(4):
                    next_c = ni + n_c[i]
                    next_r = nj + n_r[i]
                    if next_c >= 0 and next_c < len(matrix) and next_r >= 0 and next_r < len(matrix[0]):
                        q.append([l+1, [next_c, next_r]])
            return res


        res = matrix
        for i in range(len(res)):
            for j in range(len(res[i])):
                if res[i][j] != 0:
                    res[i][j] = find_nearest0(i, j, matrix, 0)
        return res

'알고리즘 Algorithm > PS' 카테고리의 다른 글

[BOJ/백준] 13458. 시험감독  (0) 2020.10.17
[LeetCode] 743. Network Delay Time - BFS  (0) 2020.10.15
[KickStart] Round F 2020 - ATM Queue  (0) 2020.09.29
[백준/BOJ] 4353. 문자열 제곱  (0) 2020.09.29
[백준/BOJ] 4358. 생태학  (0) 2020.09.29

댓글

이 글 공유하기

  • 구독하기

    구독하기

  • 카카오톡

    카카오톡

  • 라인

    라인

  • 트위터

    트위터

  • Facebook

    Facebook

  • 카카오스토리

    카카오스토리

  • 밴드

    밴드

  • 네이버 블로그

    네이버 블로그

  • Pocket

    Pocket

  • Evernote

    Evernote

다른 글

  • [BOJ/백준] 13458. 시험감독

    [BOJ/백준] 13458. 시험감독

    2020.10.17
  • [LeetCode] 743. Network Delay Time - BFS

    [LeetCode] 743. Network Delay Time - BFS

    2020.10.15
  • [KickStart] Round F 2020 - ATM Queue

    [KickStart] Round F 2020 - ATM Queue

    2020.09.29
  • [백준/BOJ] 4353. 문자열 제곱

    [백준/BOJ] 4353. 문자열 제곱

    2020.09.29
다른 글 더 둘러보기

정보

butter_shower 블로그의 첫 페이지로 이동

butter_shower

  • butter_shower의 첫 페이지로 이동

검색

메뉴

  • All Categories
  • About Me
  • Guest Book

카테고리

  • 전체보기 (223)
    • 💫 주인장 이야기 (17)
    • 🌱 와글와글뻘글 (27)
    • IT Trends (11)
    • 주인장 일상 (0)
    • 📒 내 마음대로 독서 서평 (12)
    • 머신러닝 꿈나무 (30)
      • 기본 개념 (6)
      • Hands-on! (5)
      • Paper Review (5)
      • 캐린이의 Kaggle (1)
    • 알고리즘 Algorithm (33)
      • PS (8)
    • Computer Engineering (75)
      • Python (8)
      • Cloud Computing (9)
      • C (9)
      • C++ (0)
      • Java (6)
      • Django 장고 (4)
      • 임베디드 시스템 (10)
      • 병렬 처리(Parallel Processing) (9)
      • 데이터 통신 Data communication (4)
      • 유닉스 시스템 (Unix System) (3)
      • GitHub (1)
      • 마이크로 프로세서 (micro processor) (1)
      • 데이터 마이닝 (1)
    • Error Note 🚨 (3)
    • 영어 공부 (6)
      • Live Academy (6)
    • HOBBY (2)
      • Film Log (2)

최근 글

정보

_rian의 butter_shower

butter_shower

_rian

나의 외부 링크

  • Github
  • Facebook
  • Instagram
  • LinkedIn
  • Twitter

블로그 구독하기

  • 구독하기
  • RSS 피드

방문자

  • 전체 방문자
  • 오늘
  • 어제

티스토리

  • 티스토리 홈
  • 이 블로그 관리하기
  • 글쓰기
Powered by Tistory / Kakao. © _rian. Designed by Fraccino.

티스토리툴바