Feature #3: Power Up the Station

Implementing the "Power Up the Station" feature for our "Cellular Operator" project.

Description

AT&T just acquired a cellular company in a small town that owns four base stations. The company they acquired owned vintage equipment with dials that must be rotated clockwise or counterclockwise by hand to power up the base stations. There’s one dial for each of the base stations. Each dial has numbers from 0 to 9 and does not stop at either extreme; this means you can rotate clockwise at 9 to go back to 0 or counterclockwise at 0 to go to 9.

Each position on a dial represents a particular state for the corresponding base station. To power up the base stations, the dials must be taken from state 0000 to a target state, say abcd, where a, b, c, and d are digits between 0 and 9. The constraints are that only one dial may be turned (clockwise or counterclockwise) one position at a time and certain dead states are prohibited and must be avoided at all costs. The system will get stuck and fail if we land in a dead state.

We’ll be provided with a list of dead states that we need to avoid and a target state that we need to reach. You want to power up the system in the minimum number of dial turns by avoiding the dead states.

Solution

There are 10,000 digits starting from 0000 to 9999. We have to reach a target number in a minimum number of dial turns. We can consider the 10,000 digits to be nodes in a graph. If two nodes differ in one digit (wrapping around, so 0 and 9 also differ by 1) and both nodes are not dead states, there will be an edge between them. We can use BFS here to find the shortest path from the starting node 0000 to the target node.

We implement the BFS using a queue and a visited set. The main part will be generating the new nodes from the current one. Each digit on the dial can be moved forward or backward, so eight new states can be generated from a single state. We’ll keep adding the new states into the queue if they have not already been visited or explored. The new states should only be generated from nodes that are not part of the dead states.

The eight states will be generated by moving each of the four digits forward and backward once. Usually, we can simply subtract or add 1 to each number to get a new one, but the wrapping around between 0 and 9 is allowed. Therefore, we need to do something else.

Python: We can use the modulus operator (%) to compute the wrap-around values. We can take the modulus of each number with 10. In the case of a 0 wrap-around, -1 % 10 will give us 9. In the case of 9, 10 % 10 will give us 0. The rest of the numbers will not be affected by this change.

Java: We can explicitly check for the condition: if we are subtracting from 0, 9 should be returned. ...

Access this course and 1400+ top-rated courses and projects.