publicbooleancanVisitAllRooms(List<List<Integer>> rooms) { intn= rooms.size(); num = 0; vis = newboolean[n]; dfs(rooms, 0); return num == n; }
publicvoiddfs(List<List<Integer>> rooms, int x) { vis[x] = true; num++; for (int it : rooms.get(x)) { if (!vis[it]) { dfs(rooms, it); } } } }
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
int num;
voiddfs(int** rooms, int* roomsColSize, int* vis, int x) { vis[x] = true; num++; for (int i = 0; i < roomsColSize[x]; i++) { if (!vis[rooms[x][i]]) { dfs(rooms, roomsColSize, vis, rooms[x][i]); } } }
boolcanVisitAllRooms(int** rooms, int roomsSize, int* roomsColSize) { int vis[roomsSize]; memset(vis, 0, sizeof(vis)); num = 0; dfs(rooms, roomsColSize, vis, 0); return num == roomsSize; }
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution: defcanVisitAllRooms(self, rooms: List[List[int]]) -> bool: defdfs(x: int): vis.add(x) nonlocal num num += 1 for it in rooms[x]: if it notin vis: dfs(it) n = len(rooms) num = 0 vis = set() dfs(0) return num == n
classSolution { publicbooleancanVisitAllRooms(List<List<Integer>> rooms) { intn= rooms.size(), num = 0; boolean[] vis = newboolean[n]; Queue<Integer> que = newLinkedList<Integer>(); vis[0] = true; que.offer(0); while (!que.isEmpty()) { intx= que.poll(); num++; for (int it : rooms.get(x)) { if (!vis[it]) { vis[it] = true; que.offer(it); } } } return num == n; } }
[sol2-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
boolcanVisitAllRooms(int** rooms, int roomsSize, int* roomsColSize) { int vis[roomsSize], que[roomsSize]; memset(vis, 0, sizeof(vis)); int left = 0, right = 1, num = 0; vis[0] = true; que[0] = 0; while (left < right) { int x = que[left++]; num++; for (int i = 0; i < roomsColSize[x]; i++) { if (!vis[rooms[x][i]]) { vis[rooms[x][i]] = true; que[right++] = rooms[x][i]; } } } return num == roomsSize; }
[sol2-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution: defcanVisitAllRooms(self, rooms: List[List[int]]) -> bool: n = len(rooms) num = 0 vis = {0} que = collections.deque([0])
while que: x = que.popleft() num += 1 for it in rooms[x]: if it notin vis: vis.add(it) que.append(it) return num == n
[sol2-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
funccanVisitAllRooms(rooms [][]int)bool { n := len(rooms) num := 0 vis := make([]bool, n) queue := []int{} vis[0] = true queue = append(queue, 0) for i := 0; i < len(queue); i++ { x := queue[i] num++ for _, it := range rooms[x] { if !vis[it] { vis[it] = true queue = append(queue, it) } } } return num == n }