1971. Find if Path Exists in Graph

양성준·2025년 6월 9일

코딩테스트

목록 보기
79/102

문제

https://leetcode.com/problems/find-if-path-exists-in-graph/description/

풀이

class Solution {
    boolean flag;
    public boolean validPath(int n, int[][] edges, int source, int destination) {
        List<List<Integer>> graph = new ArrayList<>();
        boolean[] ch = new boolean[n]; 
        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]);
        }

        DFS(graph, ch, source, destination, source);

        return flag;
    }

    public void DFS(List<List<Integer>> graph, boolean[] ch, int source, int destination, int n) {
        if(flag) return;
        
        if(n == destination) {
            flag = true;
            return;
        }
        ch[n] = true;
        for(int x : graph.get(n)) {
            if(ch[x] != true) {
                DFS(graph, ch, source, destination, x);
            }
        }
        return;
    }
}
  • DFS 돌려서 destination에 도착하면 flag를 true로 변경
profile
백엔드 개발자

0개의 댓글