[LeetCode] 1971. Find if Path Exists in Graph

Chobby·2일 전
1

LeetCode

목록 보기
641/652

😎풀이

  1. 간선 연결
  2. 방문 객체 정의
  3. source를 시작으로 이웃한 노드 탐색
    3-1. 연결된 간선을 queue에 추가
    3-2. queue를 기준으로 선입 선출하며 이웃 노드 탐색
    3-3. destination에 도달했다면, true 반환
  4. destination까지 도달할 수 없는 구조라면, false 반환환
function validPath(n: number, edges: number[][], source: number, destination: number): boolean {
    if (source === destination) return true

    const graph = new Map()
    for (let i = 0; i < n; i++) {
        graph.set(i, [])
    }
    for (const [from, to] of edges) {
        graph.get(from)!.push(to)
        graph.get(to)!.push(from)
    }
    
    const visit = new Set<number>()
    const queue = [source]
    let frontIndex = 0

    visit.add(source)

    while(frontIndex < queue.length) {
        const vertex = queue[frontIndex++]

        const neighbors = graph.get(vertex)
        if (!neighbors) continue
        for (const neighbor of neighbors) {
            if (neighbor === destination) return true
            if (!visit.has(neighbor)) {
                visit.add(neighbor)
                queue.push(neighbor)
            }
        }
    }

    return false;
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글