코딩테스트

[leetcode] 841. Keys and Rooms

nayoon 2024. 5. 26. 16:39

링크

 

import java.util.*;

class Solution {
    public static boolean[] unlocked;
    public static List<List<Integer>> room;
    public boolean canVisitAllRooms(List<List<Integer>> rooms) {
        int size = rooms.size();
        room = rooms;

        unlocked = new boolean[size];
        unlock(0);

        boolean result = true;
        for(boolean check: unlocked) {
            if (!check) {
                result = false;
                break;
            }
        }

        return result;
    }

    public void unlock(int visitedRoom) {
        if (unlocked[visitedRoom]) {
            return;
        }
        unlocked[visitedRoom] = true;

        List<Integer> keys = room.get(visitedRoom);

        for(int key: keys) {
            unlock(key);
        }
    }

}