LeetCode 풀기 - 1971. Find if Path Exists in Graph

백지우·2026년 9월 10일

LeetCode

목록 보기
39/76
  • LeetCode 최소 하루에 하나는 풀자는 마인드
  • 사용언어: JAVA

1971. Find if Path Exists in Graph

풀이

  • 방법: List<List>를 이용해서 adjacency list를 만듦. 각 edge를 adjacency에 넣은 후 source부터 BFS탐색을 통하여 destination 까지 가는 루트가 있는지 탐색
class Solution {
    public boolean validPath(int n, int[][] edges, int source, int destination) {
        boolean[] visited = new boolean[n];
        List<List<Integer>> graph = new ArrayList<>();

        for (int i = 0; i < n; i++) {
            graph.add(new ArrayList<>());
        }

        for(int[] edge: edges){
            graph.get(edge[0]).add(edge[1]);
            graph.get(edge[1]).add(edge[0]);
        }
        
        Queue<Integer> queue = new ArrayDeque<>();
        queue.offer(source);
        visited[source] = true;

        while(!queue.isEmpty()){
            int cur = queue.poll();

            if(cur == destination) return true;

            for(int next: graph.get(cur)){
                if(!visited[next]){
                    visited[next] = true;
                    queue.offer(next);
                }
            }
        }
        return false;
    }
}
  • 코드 작성하다가 느낀점
    - 뭐 이용해야하는지가 헷갈린다...

0개의 댓글