waveofmymind
기록하는 습관
waveofmymind
전체 방문자
오늘
어제
  • 분류 전체보기 (124)
    • 📝 정리 (5)
    • 🌊TIL (9)
    • 💻CS (1)
      • 자료구조 (1)
    • 📙Language (9)
      • ☕Java (6)
      • 🤖Kotlin (3)
    • 🍃Spring (28)
    • 👨🏻‍💻알고리즘 (67)
      • 프로그래머스 (59)
      • 백준 (3)
    • 👷DevOps (4)
      • 🐳Docker (2)
      • 🤵Jenkins (1)

블로그 메뉴

  • 홈
  • Spring
  • Java
  • 알고리즘

공지사항

인기 글

태그

  • spring
  • 힙
  • sql
  • SpringAOP
  • 스프링
  • BFS
  • 스택
  • 완전탐색
  • 스프링 시큐리티
  • 트랜잭션
  • CORS
  • Open AI
  • JDBC
  • mybatis
  • 통합테스트
  • AOP
  • 코틀린
  • 트랜잭션 전파
  • kotlin
  • spring boot
  • 스프링 부트
  • LeetCode
  • kotest
  • resultset
  • Connection
  • Spring Security
  • chat GPT
  • til
  • 챗GPT
  • 다이나믹 프로그래밍

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
waveofmymind

기록하는 습관

[LeetCode] 1091. Shortest Path in Binary Matrix
👨🏻‍💻알고리즘

[LeetCode] 1091. Shortest Path in Binary Matrix

2023. 2. 24. 01:25

문제 링크: https://leetcode.com/problems/shortest-path-in-binary-matrix/description/

 

Shortest Path in Binary Matrix - LeetCode

Can you solve this real interview question? Shortest Path in Binary Matrix - Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1. A clear path in a binary matrix is a path from

leetcode.com

코드

from collections import deque

class Solution:
    def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
        short_dist = 1234567890
        dx = [0,0,-1,1,-1,1,1,-1]
        dy = [1,-1,0,0,1,-1,1,-1]
        q = deque()
        n = len(grid)

        if grid[0][0] != 0:
            return -1

        visited = [[False] * n for _ in range(n)]
        visited[0][0] = True

        q.append((0,0,1))
        while q:
            x,y,d = q.popleft()
            if x == n-1 and y == n-1:
                short_dist = min(short_dist,d)
                break
            for i in range(8):
                nx = x + dx[i]
                ny = y + dy[i]
                if 0<=nx<n and 0<=ny<n:
                    if grid[nx][ny] == 0 and not visited[nx][ny]:
                        visited[nx][ny]==True
                        q.append((nx,ny,d+1))
        return short_dist

 

풀이

  • 네방향 탐색에서 업그레이드 되어 대각선으로도 움직일 수 있다고 하므로, dx,dy에 대각선으로 움직이는 값도 넣어준다.
  • 그리고 큐에 넣을때에는 좌표뿐만 아니라 해당 좌표까지의 거리를 넣어준다.
  • 그리고 q.popleft() 직후 x,y가 목적지 좌표에 도달했을 경우 최단거리 값을 갱신해준다.

'👨🏻‍💻알고리즘' 카테고리의 다른 글

[LeetCode] 70. Climbing Stairs  (0) 2023.02.28
[LeetCode] 841. Keys and Rooms  (0) 2023.02.24
[LeetCode] 200. Number of Islands  (0) 2023.02.24
[LeetCode] Medium. Daily Temperatures  (1) 2023.02.16
    '👨🏻‍💻알고리즘' 카테고리의 다른 글
    • [LeetCode] 70. Climbing Stairs
    • [LeetCode] 841. Keys and Rooms
    • [LeetCode] 200. Number of Islands
    • [LeetCode] Medium. Daily Temperatures
    waveofmymind
    waveofmymind

    티스토리툴바