[LeetCode] Count Houses in a Circular Street

2728. Count Houses in a Circular Street

You are given an object street of class Street that represents a circular street and a positive integer k which represents a maximum bound for the number of houses in that street (in other words, the number of houses is less than or equal to k). Houses’ doors could be open or closed initially.

Initially, you are standing in front of a door to a house on this street. Your task is to count the number of houses in the street.

The class Street contains the following functions which may help you:

  • void openDoor(): Open the door of the house you are in front of.
  • void closeDoor(): Close the door of the house you are in front of.
  • boolean isDoorOpen(): Returns true if the door of the current house is open and false otherwise.
  • void moveRight(): Move to the right house.
  • void moveLeft(): Move to the left house.

Return ans which represents the number of houses on this street.

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
/**
* Definition for a street.
* class Street {
* public:
* Street(vector<int> doors);
* void openDoor();
* void closeDoor();
* bool isDoorOpen();
* void moveRight();
* void moveLeft();
* };
*/
class Solution {
public:
int houseCount(Street* street, int k) {
for(int i = 0; i < k; i++) {
if(street->isDoorOpen()) street->closeDoor();
street->moveRight();
}
street->openDoor();
int res = 1;
while(1) {
street->moveRight();
if(street->isDoorOpen()) break;
res++;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/05/14/PS/LeetCode/count-houses-in-a-circular-street/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.