LeetCode题解之Keys and Rooms

1、题目描述

 

2、问题分析

使用深度优先遍历

 

3、代码

 1 bool canVisitAllRooms(vector<vector<int>>& rooms) {
 2         int nums = rooms.size();
 3         if ( nums == 1)
 4             return true;
 5         vector<int> R(nums, 0);
 6         R[0] = 1;
 7         
 8         stack<int> s;
 9         s.push(0);
10         
11         while (!s.empty()) {
12             int room = s.top();
13             s.pop();
14             for(auto n : rooms[room])
15                 if (R[n] == 0) {
16                     R[n] = 1;
17                     s.push(n);
18                 }
19         }
20        
21         
22         return count(R.begin(), R.end(), 1) == R.size();
23         
24         
25     }
26     

 

posted @ 2019-03-03 21:27  山里的小勇子  阅读(122)  评论(0编辑  收藏  举报