2368. Reachable Nodes With Restrictions

양성준·2025년 6월 9일

코딩테스트

목록 보기
81/102

문제

https://leetcode.com/problems/reachable-nodes-with-restrictions/description/

풀이

class Solution {
    int answer = 0; 
    public int reachableNodes(int n, int[][] edges, int[] restricted) {
        List<List<Integer>> graph = new ArrayList<>();
        boolean[] ch = new boolean[n];

        for(int x : restricted) {
            ch[x] = true;
        }

        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, 0);

        return answer;
    }

    public void DFS(List<List<Integer>> graph, boolean[] ch, int n) {
        answer++;
        ch[n] = true;
        for(int x : graph.get(n)) {
            if(ch[x] != true) {
                DFS(graph, ch, x);
            }
        }
        return;
    }
}
  • restricted인 부분은 못가므로, ch 배열에서 true로 변경
  • ch 배열을 체크하면서 탐색할 수 있는 부분으로만 탐색 -> 탐색을 했다면 탐색 가능한 노드이므로 answer++
profile
백엔드 개발자

0개의 댓글