feat: add Keys and Rooms LeetCode problem (#1189)

Co-authored-by: David Leal <halfpacho@gmail.com>
This commit is contained in:
Alexander Pantyukhin 2023-01-20 08:09:32 +04:00 committed by GitHub
parent 02c01047a7
commit 103361de54
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 28 additions and 0 deletions

View File

@ -95,6 +95,7 @@
| 709 | [To Lower Case](https://leetcode.com/problems/to-lower-case/) | [C](./src/709.c) | Easy |
| 771 | [Jewels and Stones](https://leetcode.com/problems/jewels-and-stones/) | [C](./src/771.c) | Easy |
| 807 | [Max Increase to Keep City Skyline](https://leetcode.com/problems/max-increase-to-keep-city-skyline/description/) | [C](./src/807.c) | Medium |
| 841 | [Keys and Rooms](https://leetcode.com/problems/keys-and-rooms/description/) | [C](./src/841.c) | Medium |
| 852 | [Peak Index in a Mountain Array](https://leetcode.com/problems/peak-index-in-a-mountain-array/) | [C](./src/852.c) | Easy |
| 876 | [Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list/) | [C](./src/876.c) | Easy |
| 901 | [Online Stock Span](https://leetcode.com/problems/online-stock-span/) | [C](./src/901.c) | Medium |

27
leetcode/src/841.c Normal file
View File

@ -0,0 +1,27 @@
void visitRooms(int key, int** rooms, int roomsSize, int* roomsColSize, int* visitedRooms){
if (visitedRooms[key] == 1){
return;
}
visitedRooms[key] = 1;
for (int i = 0; i < roomsColSize[key]; i++){
visitRooms(rooms[key][i], rooms, roomsSize, roomsColSize, visitedRooms);
}
}
// Depth-first search
// Runtime: O(n)
// Space: O(n)
bool canVisitAllRooms(int** rooms, int roomsSize, int* roomsColSize){
int* visitedRooms = calloc(roomsSize, sizeof(int));
visitRooms(0, rooms, roomsSize, roomsColSize, visitedRooms);
int visitedRoomsNumber = 0;
for (int i = 0; i < roomsSize; i++){
if (visitedRooms[i] == 1){
visitedRoomsNumber++;
}
}
return visitedRoomsNumber == roomsSize;
}