[leetcode]841. Keys and Rooms

[leetcode]841. Keys and Rooms


Analysis

中午吃啥?—— [啊啊啊啊 paper结果真的要出来了,心塞]

There are N rooms and you start in room 0. Each room has a distinct number in 0, 1, 2, …, N-1, and each room may have some keys to access the next room.
Formally, each room i has a list of keys rooms[i], and each key rooms[i][j] is an integer in [0, 1, …, N-1] where N = rooms.length. A key rooms[i][j] = v opens the room with number v.
Initially, all the rooms start locked (except for room 0).
You can walk back and forth between rooms freely.
Return true if and only if you can enter every room.
DFS解决~

Implement

class Solution {
public:
    bool canVisitAllRooms(vector<vector<int>>& rooms) {
        int len = rooms.size();
        vector<bool> visit(len, false);
        DFS(visit, rooms, 0);
        for(auto v:visit){
            if(!v)
                return false;
        }
        return true;
    }
    void DFS(vector<bool>& visit, vector<vector<int>>& rooms, int i){
        visit[i] = true;
        for(int j=0; j<rooms[i].size(); j++){
            if(!visit[rooms[i][j]])
                DFS(visit, rooms, rooms[i][j]);
        }
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/81408074