[LeetCode] 1926. Nearest Exit from Entrance in Maze, Medium

2025. 4. 29. 14:39·CodingTest/LeetCode
반응형

1. 문제

  • 미로 정보가 .과 +로 주어질 때, .은 통로 + 벽으로 막혀있다. entrance 정보로 시작 위치가 주어질 때, 미로를 탈출할 수 있는 최소 이동 회수를 반환하라.
  • entrance 좌표는 탈출구로 간주하지 않는다.

2. 해결

const dx = [-1, 1, 0, 0];
const dy = [0, 0, -1, 1];

function nearestExit(maze: string[][], entrance: number[]): number {
    const n = maze.length;
    const queue: number[][] = [[...entrance, 0]];

    const visited = Array.from({ length: n }, () => Array(maze[0].length).fill(false));


    while(queue.length) {
        const size = queue.length;

        const [x,y,step] = queue.shift();


        if((x!== entrance[0] || y !== entrance[1]) && (x === 0 || y ===0 || x === n-1 || y === maze[x].length - 1)) {
            return step;
        }
        for(let j = 0; j<4; j++) {
            const adjustX = dx[j] + x;
            const adjustY = dy[j] + y;

            if(adjustX >= 0 && adjustX < n && adjustY >=0 && adjustY < maze[adjustX].length
            && maze[adjustX][adjustY] === '.' && !visited[adjustX][adjustY]) {
                visited[adjustX][adjustY] = true;
                queue.push([adjustX, adjustY, step + 1]);
            }
        }
        
    }

    return -1;    
};
  • 전형적인 BFS 문제. 다만, 실수한 점은 방문 체크를 큐에 넣기전에 해야하는데 이전에 해서 시간초과가 났다.
  • 또, 큐에 step 정보를 물고다니기 때문에 레발 단위 순회를 할 필요가 없었는데 불필요한 레벨 단위 탐색을 했다는 점.
저작자표시 (새창열림)
'CodingTest/LeetCode' 카테고리의 다른 글
  • [LeetCode] 215. Kth Largest Element in an Array, Medium
  • [LeetCode] 994. Rotting Oranges, Medium
  • [LeetCode] 399. Evaluate Division, Medium
  • [LeetCode] 1466. Reorder Routes to Make All Paths Lead to the City Zero, Medium
뜸부깅
뜸부깅
코딩에 대한 여러 개인적인 생각을 정리하고 공부를 하는 공간입니다!!
  • 뜸부깅
    코오오딩
    뜸부깅
  • 전체
    오늘
    어제
    • Note (429)
      • Skill (31)
        • Java & Spring (9)
        • Javascript & HTML & CSS (0)
        • React (0)
        • Next.js (22)
      • CodingTest (389)
        • 백준 온라인 저지(BOJ) (140)
        • 프로그래머스(Programmers) (79)
        • LeetCode (170)
      • Algorithm & Data Structure (6)
      • [Project] 포트폴리오 (3)
        • Front end (3)
        • Back end (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    자바
    백준1427
    프로그래머스
    백준2751
    next 14
    leetcode 2236
    component-scan
    TypeScript
    백준7576자바
    알고리즘
    medium
    BOJ
    백준7576
    Easy
    백준
    meidum
    Java
    boj1427
    백준1260
    boj2108
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
뜸부깅
[LeetCode] 1926. Nearest Exit from Entrance in Maze, Medium
상단으로

티스토리툴바