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 the top-left cell (i.e., (0, 0)) to the bottom-right cell (i.e., (n - 1, n - 1)) such that:
0.The length of a clear path is the number of visited cells of this path.
Example 1:
Input: grid = [[0,1],[1,0]] Output: 2
Example 2:
Input: grid = [[0,0,0],[1,1,0],[1,1,0]] Output: 4
Example 3:
Input: grid = [[1,0,0],[1,1,0],[1,1,0]] Output: -1
Constraints:
n == grid.lengthn == grid[i].length1 <= n <= 100grid[i][j] is 0 or 1배열, 너비 우선 탐색, 행렬
이 문제는 N x N 크기의 이진 행렬(grid)에서 좌상단(0, 0)에서 우하단(N-1, N-1)까지 이동하는 최단 경로의 길이를 구하는 것입니다.
너비 우선 탐색(BFS, Breadth-First Search) 알고리즘을 사용합니다.
deque)**를 사용하고, 중복 방문을 막기 위해 **방문 배열(visited)**을 사용합니다.(x, y)와 **현재까지 이동한 칸의 수(cnt)**를 함께 저장합니다.grid[0][0]이 1(장애물)인 경우 즉시 -1을 반환하여 불가능함을 알립니다.n, m을 저장하고, 방문 여부를 기록할 2차원 배열 visited를 False로 초기화합니다.(0, 0)과 초기 거리 1을 넣은 뒤 방문 처리합니다.directions 리스트를 정의합니다. (상, 하, 좌, 우, 좌상, 우상, 좌하, 우하)(x, y, cnt)를 꺼냅니다.(n-1, m-1)이면 현재까지의 거리 cnt를 반환합니다. BFS 특성상 처음 도착한 경로가 최단 경로입니다.(dx, dy)에 대해 다음 좌표 (sx, sy)를 계산합니다.0 <= sx < n, 0 <= sy < m), 아직 방문하지 않았는지(not visited[sx][sy]), 이동 가능한 칸인지(grid[sx][sy] == 0)를 모두 확인합니다.visited[sx][sy] = True) 후, 거리 1을 증가시킨 (sx, sy, cnt+1)을 큐에 추가합니다.-1을 반환합니다.visited가 N x N 크기로 필요합니다.directions 리스트에 대각선 벡터까지 포함하여 상하좌우 외 이동을 간편하게 구현했습니다.from collections import deque
class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
if grid[0][0] == 1:
return -1
n = len(grid)
m = len(grid[0])
visited = [[False] * m for i in range(n)]
queue = deque()
queue.append((0,0,1))
visited[0][0] = True
directions = [(0,1),(0,-1),(1,0),(-1,0),(1,1),(1,-1),(-1,1),(-1,-1)]
while queue:
x,y,cnt = queue.popleft()
if x == n-1 and y == m-1:
return cnt
for dx,dy in directions:
sx,sy = x+dx,y+dy
if 0 <= sx < n and 0 <= sy < m and not visited[sx][sy] and grid[sx][sy] == 0:
visited[sx][sy] = True
queue.append((sx,sy,cnt+1))
return -1