1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| class Solution { Set<Integer> set = new HashSet<>(); boolean[] st;
public boolean canVisitAllRooms(List<List<Integer>> rooms) { int n = rooms.size(); st = new boolean[n]; set.add(0); return dfs(0, n, rooms); }
public boolean dfs(int cur, int n, List<List<Integer>> rooms) { if (set.size() == n) { return true; }
st[cur] = true; for (int i = 0; i < rooms.get(cur).size(); i++) { set.add(rooms.get(cur).get(i)); }
for(Integer k : set) { if (!st[k]) { return dfs(k, n, rooms); } }
return false; } }
|