Shortest Path in Binary Matrix

최제원·2024년 7월 18일

algorithm

목록 보기
3/12
post-thumbnail

https://leetcode.com/problems/shortest-path-in-binary-matrix/description/

문제 이해

n x n 맵에서 시작점 (0,0) 부터 마지막 지점 (len(n)-1, len(n)-1)까지 가장 짧은 거리로 이동할수 있는 거리를 구하는 문제

문제 포인트

그래프 문제이며 dfs(깊이 우선 탐색)으로 풀게 됐다 탐색을 진행하다 마지막 지점에 도착하면 break하고 distance를 리턴해주었다

제출 코드

def shortest_distance(grid):
    n = len(grid[0])
    visited = [[False] * n for _ in range(n)]

    shortest_len = -1

    if grid[0][0] or grid[n - 1][n - 1] == 1:
        return -1

    move = [(1,0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)]

    queue = deque()
    queue.append((0, 0, 1))
    visited[0][0] = True

    while queue:
        cur_r, cur_c, cur_count = queue.popleft()

        if cur_r == n-1 and cur_c == n-1:
            shortest_len = cur_count
            break

        for dr, dc in move:
            next_r = cur_r + dr
            next_c = cur_c + dc

            if 0 <= next_r < n and 0 <= next_c < n:
                if grid[next_r][next_c] == 0 and not visited[next_r][next_c]:
                    queue.append((next_r, next_c, cur_count + 1))
                    visited[next_r][next_c] = True

    return shortest_len
profile
Why & How

0개의 댓글