Keys and Rooms

ㅋㅋ·2022년 12월 20일
0

알고리즘-leetcode

목록 보기
74/135

정수형 2차원 벡터를 받게 되는데

첫번째 축은 방으로 생각하고, 두번째 축에는 방의 키들이 있다고 가정

이 때 0번째 방은 키가 없어도 들어갈 수 있는데,

0번째 방부터 시작하여 모든 방을 순회할 수 있으면 true 아니면 false를 반환하는 문제

class Solution {
public:
    bool canVisitAllRooms(vector<vector<int>>& rooms) {
        
        vector<int> visited(rooms.size(), false);
        queue<int> keys{};
        int visitingCount{0};

        keys.push(0);
        visited[0] = true;

        while (keys.empty() == false)
        {
            int roomIndex{keys.front()};
            keys.pop();
            visitingCount++;

            for (int i = 0; i < rooms[roomIndex].size(); i++)
            {
                int nextRoom{rooms[roomIndex][i]};
                if (visited[nextRoom])
                {
                    continue;
                }

                visited[nextRoom] = true;
                keys.push(nextRoom);
            }
        }

        return (visitingCount == rooms.size());
    }
};

0개의 댓글