当前位置:网站首页>leetcode841. Keys and rooms (medium)

leetcode841. Keys and rooms (medium)

2022-07-06 07:03:00 Heavy garbage

 Insert picture description here
 Insert picture description here
 Insert picture description here
Template questions for search
Train of thought :dfs

class Solution {
    
public: 
    int flag[1005] = {
    0};
    int dfs(vector<vector<int>>& rooms, int idx) {
    
        int cnt = 1;
        flag[idx] = 1;
        for (int i = 0; i < rooms[idx].size(); ++i) {
    
            if (!flag[rooms[idx][i]]) cnt += dfs(rooms,rooms[idx][i]);
        }
        return cnt;
    }
    bool canVisitAllRooms(vector<vector<int>>& rooms) {
    
 
        return dfs(rooms, 0) == rooms.size();
    }
};

Train of thought two :bfs

class Solution {
    
public:
    int flag[1005] = {
    0};
    bool canVisitAllRooms(vector<vector<int>>& rooms) {
    

        queue<int> q;
        q.push(0);
        flag[0] = 1;
        int cnt = 0;
        while (!q.empty()) {
    
            int frt = q.front();
            q.pop();
            cnt++;
            for (int i = 0; i < rooms[frt].size(); ++i) {
    
                if (!flag[rooms[frt][i]]) {
    
                    q.push(rooms[frt][i]);
                    flag[rooms[frt][i]] = 1;
                }
            }
        }
        return cnt == rooms.size();
    }
};
原网站

版权声明
本文为[Heavy garbage]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060654495703.html