[LeetCode] Find if Path Exists in Graph

아르당·2026년 7월 24일

LeetCode

목록 보기
423/626
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

n개의 정점을 가진 양방향 그래프가 있다. 각 정점은 0부터 n - 1까지의 숫자로 지정되어 있다. 그래프의 간선은 2차원 정수 배열 edges로 표현되고, 각 edges[i] = [ui, vi]는 정점 ui와 정점 vi 사이의 양방향 간선을 나타낸다. 모든 쌍의 정점은 최대 하나의 간선으로 연결되고, 어떤 정점도 자기 자신에게 연결되는 간선을 가지고 있지 않다.
정점 source에서 정점 destination까지 유효한 경로가 존재하는지 여부를 판별하려고 한다.
edges와 정수 n, source, destination이 주어졌을 때, source에서 destination까지 유효한 경로가 존재하면 true, 그렇지 않으면 false를 반환해라.

Example

#1

Input: n = 3, edges = [[0, 1], [1, 2], [2, 0]], source = 0, destintaion = 2
Output: true
Explanation: 정점 0에서 정점 2까지 2개의 경로가 있다.
0 -> 1 -> 2
0 -> 2

#2

Input: n = 6, edges = [[0, 1], [0, 2], [3, 5], [5, 4], [4, 3]], source = 0, destination = 5
Output: false
Explanation: 정점 0에서 정점 5까지 경로가 없다.

Constraints

  • 1 <= n <= 2 * 10^5
  • 0 <= edges.length <= 2 * 10^5
  • edges[i].length == 2
  • 0 <= ui, vi <= n - 1
  • ui != vi
  • 0 <= source, destination <= n - 1
  • 중복된 간선은 없다.
  • 스스로 이어지는 간선은 없다.

Solved

class Solution {
    public boolean validPath(int n, int[][] edges, int source, int destination) {
        Map<Integer, List<Integer>> graph = new HashMap<>();

        for(int[] edge: edges){
            int u = edge[0];
            int v = edge[1];
            
            graph.computeIfAbsent(u, k -> new ArrayList<>()).add(v);
            graph.computeIfAbsent(v, k -> new ArrayList<>()).add(u);
        }

        Set<Integer> visited = new HashSet<>();

        return dfs(source, destination, graph, visited);
    }

    private boolean dfs(int node, int destination, Map<Integer, List<Integer>> graph, Set<Integer> visited){
        if(node == destination){
            return true;
        }

        visited.add(node);

        for(int neighbor : graph.getOrDefault(node, new ArrayList<>())){
            if(!visited.contains(neighbor)){
                if(dfs(neighbor, destination, graph, visited)){
                    return true;
                }
            }
        }

        return false;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글